Felipe Peña
Felipe Peña

Reputation: 2850

Laravel 5.5 - Nested query and model relation

I have 4 models.

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. A Shipment has many Status instances through StatusHistory.

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?

Upvotes: 0

Views: 371

Answers (1)

Prince Lionel N'zi
Prince Lionel N'zi

Reputation: 2588

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

Upvotes: 2

Related Questions