如何在 Laravel 中编写这个复杂的查询?
How can I write this complex query in Laravel?
我有一个完美的查询,但我需要它在 ORM Laravel 中。
我只需要在 eloquent 查询构建器中使用此查询。
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.
使用whereHas()
方法:
Product::whereHas('vendor', function($q) {
$q->where('is_block', 0);
})->get();
Product::whereDoesntHave('vendor', function($q) {
$q->where('is_block', 1);
})->get();
确保您已在 Product
模型中定义关系:
public function vendor()
{
return $this->belongsTo(Vendor::class);
}
我有一个完美的查询,但我需要它在 ORM Laravel 中。 我只需要在 eloquent 查询构建器中使用此查询。
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 forVendor
. I want to select product fromProduct
table. Each product belong to a vendor. If vendor is blocked then don't select product. Ifis_block
attribute is0
then its mean thatvendor
is not block. Ifis_blocked=1
then vendor is blocked. I need to select only products of a vendor whose is_block = 0.
使用whereHas()
方法:
Product::whereHas('vendor', function($q) {
$q->where('is_block', 0);
})->get();
Product::whereDoesntHave('vendor', function($q) {
$q->where('is_block', 1);
})->get();
确保您已在 Product
模型中定义关系:
public function vendor()
{
return $this->belongsTo(Vendor::class);
}