irjawais
irjawais

Reputation: 135

How can I write this complex query in Laravel?

I have a query working perfect but I need it in ORM Laravel. I just need this query in eloquent Query builder.

SELECT * FROM product where vendor_id in (
  SELECT vendor_id from vendor where is_block = 0
);

Scenario : There are two tables. One for Product and other for Vendor. I want to select product from Product table. Each product belong to a vendor. If vendor is blocked then don't select product. If is_block attribute is 0 then its mean that vendor is not block. If is_blocked=1 then vendor is blocked. I need to select only products of a vendor whose is_block = 0.

Upvotes: 1

Views: 65

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

Use the whereHas() method:

Product::whereHas('vendor', function($q) {
    $q->where('is_block', 0);
})->get();

Or the whereDoesntHave() method:

Product::whereDoesntHave('vendor', function($q) {
    $q->where('is_block', 1);
})->get();

Make sure you've defined the relationship in the Product model:

public function vendor()
{
    return $this->belongsTo(Vendor::class);
}

Upvotes: 3

Related Questions