如何在 Eloquent 中实现此功能?
select * from product where name like '%value%' and (product_type = product_type_param or product_type_param = 0);
如果提供 product_type_param
值为 0
,它将选择所有类型的产品,当然还要考虑到名称也匹配。
我当前的代码:
$result = Product::where( [ ['name', 'like', '%' .
$searchAttributes['name'] . '%'],
['product_type', '=', $searchAttributes['product_type']]]
)->get();
这个想法是这样的(请原谅这个例子,它只表明了我的意图):
['product_type', '=', $searchAttributes['product_type']] or [$searchAttributes['product_type'] == 0]]
我应该执行原始查询吗?
最佳答案
您可以使用闭包函数来确定查询范围
Product::where('name', 'like', '%' . $searchAttributes['name'] . '%')
->where(function($q) use ($searchAttributes) {
$q->where('product_type', $searchAttributes['product_type'])
->orWhere('product_type_param', 0);
})->get();
关于php - 如何在 Eloquent 中将 "or"与多个 "where"一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52153697/