Reputation: 477
I have a products
table and an orders
table. They have a many to many relationship between them and the product_order
table is the intermediary. Now, I have two products ids and want to select the orders that contains both of them, if it exists. How can I do that with Laravel eloquent?
class Product extends Model
{
// ...
public function orders()
{
return $this->belongsToMany('App\Order', 'product_order');
}
}
class Order extends Model
{
// ...
public function products()
{
return $this->belongsToMany('App\Products', 'product_order');
}
}
Upvotes: 0
Views: 74
Reputation: 25926
Use multiple whereHas()
constraints:
$productIds = [1, 2];
$query = Order::query();
foreach($productIds as $productId) {
$query->whereHas('products', function($query) use($productId) {
$query->where('products.id', $productId);
});
}
$orders = $query->get();
If there can only be one pivot row for each combination of order_id
and product_id
, you can use a shorter query:
$productIds = [1, 2];
$orders = Order::whereHas('products', function($query) use($productIds) {
$query->whereIn('products.id', $productIds);
}, '=', count($productIds))->get();
Upvotes: 5