也许我试图以错误的方式完成此操作,但我需要能够在 laravel 查询构建器中插入一个 if 条件:
$name = $request->input('name');
$query = DB::connection('dbconxz')
->table('all_items')->select('name', 'price', 'description', 'type', 'quantity', 'exempt')
->where('name', 'like', "%{$name}%")
->when('??? how to target the *TYPE* column?'== 'Inventory', function ($query) {
return $query->where('quantity', '>', 0);
})
->get();
我有一个 ajax 自动完成,它正在搜索表 all_items 并返回名称与用户输入的内容相似的项目集合。来自数据库的典型 ajax 自动完成。现在我的问题是,名为“type”的列中的一些行有“Inventory”这个词,我希望只在该行的数量 > 0 时才包含该结果。
有什么想法吗?
最佳答案
所以让我们用常规的 SQL 来解决这个问题。
SELECT name, price, description, type, quantity, exempt
FROM all_items
WHERE name LIKE %$name%
AND (
(
type = 'Inventory'
AND quantity > 0
)
OR type <> 'Inventory'
);
然后,使用 Laravel:
$name = $request->input('name');
$query = DB::connection('dbconxz')
->table('all_items')->select('name', 'price', 'description', 'type', 'quantity', 'exempt')
->where('name', 'like', "%{$name}%")
->where(function ($query) {
return $query->where([
'type', '=', 'Inventory',
'quantity', '>', 0
])
->orWhere('type', '<>', 'Inventory');
})
->get();
关于php - 如何使用 laravel 查询生成器 'when' 运算符定位同一结果集的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44915277/