循环where子句?

时间:2016-09-06 12:27:04

标签: laravel laravel-5 laravel-5.3

我指定了一个where子句:

$this->model = $model->where('published', '=', '1');
$this->model->get();

以上工作正常,给出查询日志:

select * from `products` where `published` = ?"

但我需要遍历数组中的where子句。

$arr = [['published', '=', '1'], ['id', '=', '1']];
foreach ($arr as $key => $value) {
    $model = $model->where($value);
}
$model->get();

但是上面我找到了一个未找到的专栏。 'where子句'中的未知列'0'。

我哪里错了?

除此之外,如果我只是传入整个数组,它可以工作:

$model = $model->where($arr);

提供以下的查询日志:

"select * from `products` where (`published` = ? and `id` = ?)"

但where子句在括号中......为什么?

3 个答案:

答案 0 :(得分:3)

解决方案1 ​​

$query = new Model;

foreach($arr as $condition){
   $query->where($condition[0], $condition[1], $condition[2]);
}

$query->get();

这将创建如下所示的查询

Select * from table where published = 1 and id = 1;

您可以在此处看到值不在括号中,因为它们不是合并后的结果。

解决方案2

此解决方案将为where子句创建组合,最终结果将在括号中

$query = new Model;
$query->where(function($q) use ($arr){
    foreach($arr as $condition){
        $q->where($condition[0], $condition[1], $condition[2]);
    }
}

$query->get();

这将导致您完成的确切查询。这是因为解决方案是对查询中发生的事情进行细分 $ this-> model->其中($ arr)

Select * from table where (published = 1 and id = 1);

要进一步了解为什么会发生这种情况,请查看以下示例

Select * from table where (id = 2 or product_id = 3) and (publish = 1 and status = 2)

通过此查询,您可以看到它是解决方案1和解决方案2的混合物。您解决它是

$query = new Model;
$query->where(function($q) use($input) {
    $q->where('id', '=', $input['id1'])
       ->orWhere('id' , '=', $input['id2']);
}

直到现在我们已经创建了以下结果

Select * from table where (id = 1 or id = 2)

现在要添加查询的下一部分,我们将执行以下操作

//continued from above
//$query has the above condition which can be continued after the first where for chaining or in next line.
$query->where(function($q) use($input){
    $q->where('publish' ,'=', 1)->where('status','=',1);
}

现在有了这个,最后的查询就变成了我们需要的查询。希望现在很清楚为什么会添加括号。

答案 1 :(得分:2)

我刚刚设法让事情发挥作用:

\DB::enableQueryLog();

$model = (new User)->newQuery();

$wheres = [
    ['forename', '=', 'Joe'],
    ['surname', '=', 'Bloggs'],
    ['email', '=', 'test@test.com']
];

foreach ($wheres as $where) {
    // Call $model->where(...) passing in each array item as a separate param
    call_user_func_array([$model, 'where'], $where);
}

$result = $model->get();

dd(\DB::getQueryLog(), $result);

这导致查询:

select * from `users` where `forename` = ? and `surname` = ? and `email` = ?

在创建运行查询的模型实例时,诀窍似乎是添加->newQuery()部分。

注意,call_user_func_array将数组的每个项目传递给$model->where(...)。我发现将数组传递给->where(...)会导致构建器尝试添加多个where子句。使用call_user_func_array的另一个好处是,它会传递您希望在每个子句中提供的许多参数 - 不需要精确为3。

答案 2 :(得分:0)

我认为你错过了专栏名称 试试这个:

foreach ($arr as $key => $value) {
    $model = $model->where($value[0],$value[1],$value[2]);
}
相关问题