You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel MongoDB中能否结合Eloquent的where/with与raw方法?

在Laravel Eloquent中结合MongoDB的where过滤与Lookup关联查询

直接使用Product::where()->raw()无法生效的原因是:Eloquent的where构建的是普通查询语句,而raw()中的聚合操作是独立的管道流程,两者不会自动合并。要实现过滤+关联的需求,你可以通过以下两种方式解决:

方法一:在聚合管道中手动添加$match阶段

将过滤条件直接写入聚合管道的$match阶段,放在$lookup之前执行(先过滤再关联,性能更优),示例代码:

$filterValue = '目标过滤值';
$products = Product::raw(function($collection) use ($filterValue) {
    return $collection->aggregate([
        // 第一步:过滤产品
        [
            '$match' => [
                'filter' => $filterValue
                // 可添加更多过滤条件,比如 'price' => ['$gt' => 100]
            ]
        ],
        // 第二步:关联分类数据
        [
            '$lookup' => [
                'from' => 'categories',
                'localField' => 'categories.tree',
                'foreignField' => '_id',
                'as' => 'categories.tree'
            ]
        ],
        // 可选:添加排序逻辑
        [
            '$sort' => [
                'name' => 1 // 1为升序,-1为降序
            ]
        ]
    ]);
});

方法二:复用Eloquent查询构建器的条件

如果你习惯用Eloquent的where、orderBy等方法构建过滤/排序规则,可以先把查询条件转换成聚合的$match阶段,再拼接关联逻辑:

$filterValue = '目标过滤值';
// 用Eloquent构建基础查询条件
$query = Product::where('filter', $filterValue)
                ->where('price', '>', 100); // 可添加更多条件

// 获取查询构建器中的过滤规则,转为聚合$match阶段
$matchStage = $query->getQuery()->getFilters();

// 执行聚合查询,合并条件与关联
$products = $query->aggregate([
    ['$match' => $matchStage],
    [
        '$lookup' => [
            'from' => 'categories',
            'localField' => 'categories.tree',
            'foreignField' => '_id',
            'as' => 'categories.tree'
        ]
    ],
    // 若用Eloquent的orderBy,可转为$sort阶段
    ['$sort' => $query->getQuery()->getSort()]
]);

这两种方式都能实现先过滤产品,再关联完整分类数据的需求,同时支持添加排序、分页等其他聚合操作。

内容的提问来源于stack exchange,提问作者Victor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 20:42:32