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

Laravel 5.5 - Nested query and model relation

我有4个模型。

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');
}

一个User有多个ShipmentShipment 有许多 Status 个实例到 StatusHistory

如何通过 Eloquent 关系获得 User 的所有 Shipment 值,这些值在 StatusHistory 模型中具有特定的 id 值?

你可以做到

$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();