Home > Software engineering >  Laravel OneToMany query
Laravel OneToMany query

Time:01-19

I'm new to Laravel and the Eloquent model and I find it difficult to understand the simplest queries even after reading the documentation.

I have two models Measure and MeasureType, and I want to select all measures of a certain type. What in sql would be like:

select * from measures m
      join measure_types mt on mt.id=m.measure_type_id
      join measure_type_trans t on t.measure_type_id=mt.id
      where t.name='xyz';

In Measure I have:

public function type()
    {
        return $this->belongsTo(MeasureType::class, 'measure_type_id');
    }

And in MeasureType:

public function measures()
    {
        return $this->hasMany(Measure::class);
    }

Name column is in the translatable table measure_type_trans How do I do such simple query?

CodePudding user response:

If you want the type and nested in it the measures that belong to it

$measureType = MeasureType::where('name', 'xyz')->with('measures')->first();

//you can access the measures with the attribute having the same name as the relation
$measures = $measureType->measures;

If you want to have only the measures as a collection (almost the same as the query you posted)

$measures = Measure::whereHas('type', function ($typeQueryBuilder) {
    $typeQueryBuilder->where('name', 'xyz');
})->get();
  •  Tags:  
  • Related