php - 如何在 Laravel 6.x 中将模型的关联条件添加到 Eloquent 查询中?
问题描述
在我的 Laravel 6.x 项目中,我有Product
模型ProductCategory
和WarehouseProduct
模型。
在Product
我存储我的产品的基本信息。在ProductCategory
模型中,我存储产品的类别信息。在WarehouseProduct
I 中存储有关仓库中产品的库存数量信息。当然,我有很多仓库,里面有很多产品。
我的产品如下所示:
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');
}
}
ProductCategory 如下所示:
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 条件:该类别的产品?
解决方案
$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();
请注意,我使用的是条件子句when
的方法,但是您可以像以前一样继续使用s 。if
推荐阅读
- linux - 如何在 apache 中选择通配符证书和子域证书
- html - Google 电子邮件标记发票类型未显示在日历中
- angular - 如何在Angular的模态窗口中使用该功能
- python - python dataframe.at 赋值与数据类型更改
- asp.net - 未捕获的异常是否会终止整个 ASP.NET Core webapp?
- python - 安装 geopandas 撤消 jupyter 安装
- vue.js - 使用带有一个道具的组件
- java - 从导出的 jar 运行时,将希伯来语写入文件会变成乱码
- eclipse - 比较不在 Eclipse 氧气/光子中工作
- laravel - laravel 中的角色与多重身份验证