I'm working in Laravel 4, I can my models simplify to these:
class DayVariant extends \Eloquent {
public function chod()
{
return $this->belongsTo('Chod', 'chod_id');
}
}
class Chod extends \Eloquent {
public function meals()
{
return $this->belongsToMany('Meal');
}
}
class Meal extends \Eloquent {
public function mealProperties()
{
return $this->hasMany('MealsProperty');
}
}
class MealProperty extends \Eloquent {
public function propertyType()
{
return $this->belongsTo('PropertyType', 'property_type_id');
}
}
And I want select MealProperty by property_type_id. I was doing it this way:
$prop = $dayVariant->chod->meals->first()->mealProperties()->where('property_type_id','=', $foo)->first();
I need in this way get 5 from 70 the same mealsProperties for every meal. It works well, but I don't know how use eager loading for decreasing queries to database.
$dayVariant = DayVariant::with('breakfastChod.meals.mealProperties')->first();
I can do it this way and after it iterate over all mealProperties, but I'm looking for better way.
Maybe with constraints I can get only mealProperties which I will need and iterate over them.
Is there better way to get specific properties? If not, how can use constraints with my models?
I tried this, but it fails.
$dayVariant = DayVariant::whereHas('breakfastChod.meals.mealProperties', function($query)
{
$query->where('property_type_id', '=', $constants['nutr_ids']['kcal']);
})->first();
Thanks for every answer!