使用Laravel-MongoDB查询含非空images字段的MongoDB记录
解决方案
针对你的需求,有几种更可靠的方式来构建查询,避开$expr可能带来的兼容性问题:
方法一:直接排除空数组
利用MongoDB对空数组的原生判断,结合exists条件,代码简洁且高效:
$advertisements = Advertisement::query() ->where('status', Advertisement::ACTIVE) ->where('images', 'exists', true) ->where('images', '!=', []);
也可以使用MongoDB原生操作符$ne实现同样效果:
$advertisements = Advertisement::query() ->where('status', Advertisement::ACTIVE) ->where('images', 'exists', true) ->where('images', '$ne', []);
方法二:明确检查数组长度大于0
如果需要精准判断数组元素数量,可直接使用$size结合$gt的原生查询逻辑,无需包裹$expr:
$advertisements = Advertisement::query() ->where('status', Advertisement::ACTIVE) ->where('images', 'exists', true) ->whereRaw(['$gt' => [['$size' => '$images'], 0]]);
原代码失效原因
部分版本的laravel-mongodb包对$expr的解析支持不够完善,直接传递MongoDB原生操作符数组给whereRaw,能绕过ORM层的解析问题,查询稳定性更高。
内容的提问来源于stack exchange,提问作者Hossein
相关产品推荐
相关产品推荐

