首页 > 解决方案 > 如何在 Laravel 6.x 中将模型的关联条件添加到 Eloquent 查询中?

问题描述

在我的 Laravel 6.x 项目中,我有Product模型ProductCategoryWarehouseProduct模型。

Product我存储我的产品的基本信息。在ProductCategory模型中,我存储产品的类别信息。在WarehouseProductI 中存储有关仓库中产品的库存数量信息。当然,我有很多仓库,里面有很多产品。

我的产品如下所示:

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 条件:该类别的产品

标签: phplaraveleloquentlaravel-6laravel-query-builder

解决方案


您可以查询关系存在。由于它是通过Product另一个模型

$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


推荐阅读