【发布时间】:2014-04-25 20:20:28
【问题描述】:
我正在使用 Laravel 4,我可以将我的模型简化为这些:
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');
}
}
我想通过 property_type_id 选择 MealProperty。我是这样做的:
$prop = $dayVariant->chod->meals->first()->mealProperties()->where('property_type_id','=', $foo)->first();
我需要以这种方式从 70 个中获得 5 个相同的mealsProperties。它运作良好,但我不知道如何使用预先加载来减少对数据库的查询。
$dayVariant = DayVariant::with('breakfastChod.meals.mealProperties')->first();
我可以这样做,并且在它遍历所有 mealProperties 之后,但我正在寻找更好的方法。 也许有限制,我只能得到我需要的 mealProperties 并遍历它们。 有没有更好的方法来获取特定属性?如果没有,如何在我的模型中使用约束? 我试过了,但是失败了。
$dayVariant = DayVariant::whereHas('breakfastChod.meals.mealProperties', function($query)
{
$query->where('property_type_id', '=', $constants['nutr_ids']['kcal']);
})->first();
感谢您的每一个回答!
【问题讨论】:
-
您已经拥有 MealProperties 的这些 ID 了吗?您只需要这些属性还是所有相关模型?
-
嗨,德克佐。是的,我有我需要的每个属性的 property_type_id 并且我需要所有相关模型。
标签: laravel laravel-4 eloquent eager-loading