简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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