John Davidson

php - Laravel OneToMany query

0 comments
Message:


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?



My Answer:
>hasMany('App\MeasureType');_ }_And in MeasureType I have:_public function measures()_ {_ return $this->belongsTo('App\Measure');_ }_To select all measures of a certain type in Laravel using Eloquent, you can use the following query:_$measures = Measure::whereHas('type', function ($query) {_ $query->whereHas('trans', function ($query) {_ $query->where('name', 'xyz');_ });_})->get();_This query uses the `whereHas` method to filter the measures based on the related type and its translation. It checks if the type has a translation with the name 'xyz' and retrieves the measures associated with that type.

Rate this post

4 of 5 based on 6310 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us