雄辩的关系优化查询

Igo*_*rse 10 laravel eloquent laravel-5

我有以下型号:CardBoard,User,UserPricingPlans,PricingPlanLimits

注意:不要介意模型代码是否有问题.它们工作正常.

纸板

class CardBoard extends Model{

   public function user(){

      return $this->belongsTo('Models\User','id_user');

   }
}
Run Code Online (Sandbox Code Playgroud)

用户

class User extends Model{

   public function pricingPlans(){

      return $this->hasMany('Models\UserPricingPlan','id_user');

   }
}
Run Code Online (Sandbox Code Playgroud)

PricingPlan

class PricingPlan extends Model{

   public function limits(){

      return $this->hasOne('Models\PricingPlanLimits','id_pricing_plan','id_pricing_plan');

   }
}
Run Code Online (Sandbox Code Playgroud)

PricingPlanLimits

我不会描述那个模型,它不是问题所必需的.但请记住,有一个名为maxBoards的属性.

问题是我只有CardBoard模型实例可以使用,我想从PricingPlanLImits 获取maxBoard属性.所以我这样做了:

注意:我已经有了CardBoard模型实例!

$maxBoard = $cardBoard->user->pricingPlans->last()->limits->maxBoard;

return $maxBoard;
Run Code Online (Sandbox Code Playgroud)

上面的代码运行得很好,但是这个操作生成的查询数量对我来说是个开销.Eloquent 为每个调用的关系做一个SELECT,我不想要所有这些数据和操作.

{
    "query": "select * from `users` where `users`.`id_user` = ? limit 1",
    "bindings": [
    ],
    "time": 0.96
}   
{
    "query": "select * from `users_princing_plan` where `users_princing_plan`.`id_user` = ? and `users_princing_plan`.`id_user` is not null",
    "bindings": [
    ],
    "time": 0.8
}
{
    "query": "select * from `pricing_plan_limits` where `pricing_plan_limits`.`id_pricing_plan` = ? and `pricing_plan_limits`.`id_pricing_plan` is not null limit 1",
    "bindings": [

    ],
    "time": 0.88
}
Run Code Online (Sandbox Code Playgroud)

难道没有办法优化这个并在Eloquent-Way中运行更少的查询?

Sha*_*mor 1

如果使用with()方法,您可以在一次查询中获取数据。

例如CardBoard::with('user.pricingPlans')->get();

所以可以使用with方法优化您的查询。