1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Laravel get collection keys when second key matches value

Discussão em 'Outras Linguagens' iniciado por Kingfisher VA, Outubro 13, 2024 às 14:52.

  1. Hello i like to get all key values if other key matches string.

    here is an example function thats get only values from the model:

    $where = [];
    $where['state'] = PirepState::ACCEPTED;
    $where['airline_id'] = $airline_id;
    $where['source'] = PirepSource::ACARS;

    $average_lrate = Pirep::where($where)->avg('landing_rate');
    $stats[__('DBasic::widgets.alrate')] = number_format(abs($average_lrate)) . ' ft/min';


    This i have tryed to change to access a collection and get all key values if second key matches a string:

    $where = [];
    $where['state'] = PirepState::ACCEPTED;
    $where['airline_id'] = $airline_id;
    $where['source'] = PirepSource::ACARS;

    $average_grate = Pirep::where($where)->avg('fields->where(slug, "landing-g-force")->value(value)->all()');
    $stats[__('DBasic::widgets.agrate')] = number_format(abs($average_grate)) . ' g';


    Thats the model of the fields attribute:

    /**
    * Get the pirep_fields and then the pirep_field_values and
    * merge them together. If a field value doesn't exist then add in a fake one
    */
    public function fields(): Attribute
    {
    return Attribute::make(get: function ($_, $attrs) {
    $custom_fields = PirepField::whereIn('pirep_source', [$this->source, PirepFieldSource::BOTH])->get();
    $field_values = PirepFieldValue::where('pirep_id', $this->id)->orderBy(
    'created_at',
    'asc'
    )->get();

    // Merge the field values into $fields
    foreach ($custom_fields as $field) {
    $has_value = $field_values->firstWhere('slug', $field->slug);
    if (!$has_value) {
    $field_values->push(
    new PirepFieldValue([
    'pirep_id' => $this->id,
    'name' => $field->name,
    'slug' => $field->slug,
    'value' => '',
    'source' => PirepFieldSource::MANUAL,
    ])
    );
    }
    }

    return $field_values;
    });
    }


    Thats the model of 'field':

    /**
    * Return a custom field value
    *
    * @param $field_name
    *
    * @return string
    */
    public function field($field_name): string
    {
    $field = $this->fields->where('name', $field_name)->first();
    if ($field) {
    return $field['value'];
    }

    return '';
    }


    This and many more i tryed:

    $average_grate = Pirep::where($where)->avg('fields->where(slug, "landing-g-force")->value(value)->all()');


    resulted in: Column not found: 1054 Unknown column 'fields' in 'field list'

    $average_grate = Pirep::where($where)->avg('fields.value->where(slug, "landing-g-force")->get()');


    resulted in: Column not found: 1054 Unknown column 'fields.value' in 'field list'

    Continue reading...

Compartilhe esta Página