php - 如何使用 laravel 查询生成器 'when' 运算符定位同一结果集的列

标签 php mysql ajax laravel

也许我试图以错误的方式完成此操作,但我需要能够在 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/

相关文章:

php - 用于获取 Google for Business 的所有评论和评级的 API

php - Laravel 资源 Controller ajax 调用

javascript - 带有 codeigniter 3 的图表栏

javascript - 将 PHP 的 MySQL 结果插入 JavaScript 数组

javascript - 在 Ajax 中实现这个精确的 PHP foreach 功能?

javascript - 数据是否自动推送到网站? (Python/Flask + WSIG + jquery AJAX)

php - 统计mysql表中的记录数

mysql - 选择符合时间表mysql的用户

mysql - 从 mySQL 中提取 COUNT(列) 到 VB.NET

javascript - jQuery/Javascript : More complex Searching and Replacing in an HTML document