在我的 Laravel 6.x 项目中,我有 Product
模型、ProductCategory
和 WarehouseProduct
模型。
在Product
中,我存储产品的基本信息。在 ProductCategory
模型中,我存储产品的类别信息。在 WarehouseProduct
中,我存储仓库中产品的库存量信息。当然我有很多仓库,有很多产品。
我的产品如下所示:
class Product extends Model
{
protected $fillable = [
'name',
'item_number',
// ...
];
public function categories() {
return $this->belongsToMany(ProductCategory::class, 'product_category_products',
'product_id', 'product_category_id');
}
}
产品类别如下所示:
class ProductCategory extends Model
{
protected $fillable = [
'name',
'description',
// ...
];
public function products() {
return $this->belongsToMany(Product::class, 'product_category_products',
'product_category_id', 'product_id');
}
}
WarehouseProduct 看起来像这样:
class WarehouseProduct extends Model
{
protected $fillable = [
'product_id',
'warehouse_id',
'amount',
// ...
];
public function product() {
return $this->belongsTo(Product::class, 'product_id');
}
}
我现在有这个查询:
$query = WarehouseProduct::select([
'product_id',
'warehouse_id',
DB::raw('SUM(free_amount)'),
DB::raw('SUM(booked_amount)'),
// ...
]);
if (isset($request->warehouse_id)) {
$query->where([['warehouse_id', '=', $request->warehouse_id]]);
}
if (isset($request->product_category_id)) {
// ???
}
如何向查询内容添加 where 条件:此类别的产品?
最佳答案
您可以查询Relationship Existence 。由于它是通过另一个模型 (Product
) 建立的关系,如果您定义了 Has Many Through,则可以减少查询。关系,但我认为这对于这个特定的查询来说就足够了。
$warehouse_id = $request->warehouse_id;
$product_category_id = $request->product_category_id;
$query = WarehouseProduct::select([
'product_id',
'warehouse_id',
DB::raw('SUM(free_amount)'),
DB::raw('SUM(booked_amount)'),
// ...
])
->when($warehouse_id, function ($query) use ($warehouse_id) {
$query->where('warehouse_id', $warehouse_id);
})
->when($product_category_id, function ($query) use ($product_category_id) {
$query->whereHas('product', function ($que) use ($product_category_id) {
$que->whereHas('categories', function ($q) use ($product_category_id) {
$q->where('id', $product_category_id);
})
})
});
$results = $query->get();
请注意,我对 conditional clauses 使用 when
方法,但您可以像以前一样继续使用 if
。
关于php - 如何在 Laravel 6.x 中的 Eloquent 查询中添加模型相关条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62065992/