【问题标题】:Select item by specific property按特定属性选择项目
【发布时间】: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


【解决方案1】:

您可以在属性的上下文中执行此操作,或者像您尝试的 dayVariant 一样:

// starting from properties
$properties = MealProperty::whereIn('property_type_id',$foo)
                 ->with('meal.chods.dayVariants')->get();

// or from dayVariant
$dayVariant = DayVariant::with(['chod.meals.mealProperties' => function ($q) use ($foo) {
  $q->whereIn('property_type_id', $foo);
}])->first();

【讨论】:

  • 它对我有用,非常感谢!我仍然有 52 个查询,但比 300 个更好:)
  • 可能是因为我设计了DayVariant 模型错误。而不是方法chod,我有真正的breakfastChodtea-timeChod,...,dinnerChod。对于每个***Chod,它执行相同的查询,所以我认为如果我将实现一个方法chods 而不是前面提到的方法,我可以获得大约 15 个查询。你怎么看?是否可以在实际模型中加入查询?谢谢@deczo
  • laravel.io/bin/lz578 我复制了所有重要的内容,抱歉代码太长了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-24
  • 2020-06-12
  • 2011-03-31
  • 2018-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多