简体   繁体   English

Laravel 5.5-嵌套查询和模型关系

[英]Laravel 5.5 - Nested query and model relation

I have 4 models. 我有4个模型。

  • User 用户
  • Shipment 装船
  • Status 状态
  • Status history 状态记录

User.php

public function shipments() {
   return $this->hasMany('App\Shipment', 'from_user_id');
}

Shipment.php

public function statuses() {
   return $this->hasMany('App\StatusHistory', 'model_id');
}

A User has many Shipment . User有很多Shipment A Shipment has many Status instances through StatusHistory . Shipment通过StatusHistory具有许多Status实例。

How can I get with an Eloquent relationship all the Shipment values for an User , that have a specific id value in the StatusHistory model? 如何通过雄辩关系获得User所有Shipment值,它们在StatusHistory模型中具有特定的id值?

You can do 你可以做

$user = User:find($id);
$shipments = $user->shipments()->whereHas('statuses', function ($query) {
    //Select all the shipments for this user where `StatusHistory` id is 1
    $query->where('id', 1);
})->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM