mysql - 将两个参数传递给嵌套的 where 会导致 "and ` ` is null"附加到查询

标签 mysql laravel where-clause

      if ($input['search']) {
            $args = array($query, $input);
            $query->where(call_user_func_array(function($query, $input) {
                $query->where('tbl_products.name', 'LIKE', '%' . $input['search'] . '%')
                    ->orwhere('sku', 'LIKE', '%' . $input['search'] . '%');
            }, $args));
        }
    }
    return $query;

上面是我的查询的一部分,我打算在其中创建一个类似于以下内容的嵌套 where 子句:

WHERE
    m.name = 'name' AND
    (p.name LIKE "% example %" or p.sku LIKE "% example %")

我已经使用“call_user_func_array”将多个参数传递给闭包(这是我可以将用户输入传递给 where 子句的唯一方法)。

不幸的是,我收到一个看起来有点像这样的查询异常:

Unknown column '' in 'where clause' ...name LIKE %example% or sku LIKE %example% and `` is null

and `` is null 已附加到末尾。我认为这与需要两个参数的原始 where 子句有关,但我正在努力解决它。任何帮助将不胜感激。

最佳答案

尝试这样的事情:

if ($input['search']) {
    $query->where(function ($query) use ($input) {
        $query->where('tbl_products.name', 'LIKE', '%' . $input['search'] . '%')
            ->orWhere('sku', 'LIKE', '%' . $input['search'] . '%');
    });
}

您可以通过use 将变量传递给闭包。

引用:Anonymous Functions .

关于mysql - 将两个参数传递给嵌套的 where 会导致 "and ` ` is null"附加到查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31389713/

相关文章:

mysql - 如何使用 Play 2.x 对 MySQL 数据库进行单元测试?

php - mysqli 数组获取未获取数据

php - 拉维尔 5.2 : Artisan Key Generation for Application Key not working properly

Laravel Cartalyst Sentinel 无法回滚迁移

laravel - 结合 Laravel 和 Create-React-App

sql - 如何在 where 子句中使用正则表达式来过滤 Postgres 中的行?

mysql - 如何获取按月分组的总工作时间?

MySQL - 从字符串中提取数字

mysql - 使用 WHERE 多次指定联合条件和排除列

sql - SQL 中 WHERE 子句中的 LIKE 和 NULL