[英]How to get items are not in a collection in Laravel Eloquent?
在我的 Laravel 6.x 項目中,我有Product
model、 Warehouse
和WarehouseProduct
模型。
在產品中,我存儲了我的產品的基本信息。 在 WarehouseProduct 中,我存儲有關倉庫中產品的庫存數量信息。 當然,我有很多倉庫,里面有很多產品。
我的Product
如下所示:
class Product extends Model
{
protected $fillable = [
'name',
'item_number',
// ...
];
}
Warehouse
長這樣:
class Warehouse extends Model
{
protected $fillable = [
'name',
'address',
// ...
];
public function products() {
return $this->hasMany(WarehouseProduct::class);
}
public function missingProduct() {
// here I need to return a Product collection which are not in this Warehouse or the
// stored amount is 0
}
}
最后WarehouseProduct
看起來像這樣:
class WarehouseProduct extends Model
{
protected $fillable = [
'product_id',
'warehouse_id',
'amount',
// ...
];
public function product() {
return $this->belongsTo(Product::class, 'product_id');
}
public function warehouse() {
return $this->belongsTo(Warehouse::class, 'warehouse_id');
}
如何獲取未存儲在Warehouse
中或數量為0
的Product
集合?
像這樣的東西應該工作:
use App\Product;
public function missingProduct() {
$excludedProducts = $this->products()->where('amount', '>', 0)->pluck('id');
return Product::whereNotIn('id', $excludedProducts)->get();
}
基於@KarolSobański 的解決方案,當您向產品 model 添加一個warehouse_products
關系時:
use App\Product;
use Illuminate\Database\Eloquent\Builder;
public function missingProduct() {
return Product::whereDoesntHave('warehouse_products', function (Builder $query) {
$query->where('warehouse_id', $this->id);
})->orWhereHas('warehouse_products', function (Builder $query) {
$query->where('warehouse_id', $this->id);
$query->where('amount', 0);
})->get();
}
最短的答案可能與此類似:
Product::doesntHave('warehouse_products')
->orWhereHas('warehouse_products', function (Builder $query) {
$query->where('amount', '=', 0)
})->get();
雖然我不確定上述是否有效。
但是以下更長的查詢肯定可以解決問題:
Product::where(function ($query) {
$query->doesntHave('warehouse_products');
})->orWhere(function ($query) {
$query->whereHas('warehouse_products', function (Builder $query) {
$query->where('amount', '=', 0);
});
})->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.