laravel 使用单个数组传递多个 WHERE 条件(使用 LIKE)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28004498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using a single array to pass multiple WHERE conditions (with LIKE)
提问by lesssugar
Theory
理论
It's been discussedthat one can use the following code to pass multiple WHERE
clauses to single where()
method in Laravel's Eloquent:
已经讨论过可以使用以下代码将多个WHERE
子句传递给where()
Laravel 的 Eloquent 中的单个方法:
$condition = array('field_1' => 'value_1', 'field_2' => 'value_2');
$users = User::where($conditon)->get();
The code above simply chains the array's key-value pairs with AND
, generating this:
上面的代码简单地将数组的键值对与 链接起来AND
,生成如下:
SELECT * FROM `users` WHERE field_1 = value_1 AND field_2 = value_2;
Problem
问题
The key-value pairs above base on equality. Is it possible to use the same implementation for strings, where instead of =
we use LIKE
?
上面的键值对基于相等。是否可以对字符串使用相同的实现,而不是=
我们使用LIKE
?
Abstract example of what I mean:
我的意思的抽象例子:
$condition = array(
array('field_1', 'like', '%value_1%'),
array('field_2', 'like', '%value_2%')
);
$users = User::where($conditon)->get();
This can for sure be done with multiple ->where(...)
usage. Is it doable with passing a single array, though?
这肯定可以通过多次->where(...)
使用来完成。但是,传递单个数组是否可行?
回答by lukasgeiter
No not really. But internally Laravel just does it with a loop as well.
不,不是。但在 Laravel 内部,它也只是通过循环来完成。
Illuminate\Database\Query\Builder@where
Illuminate\Database\Query\Builder@where
if (is_array($column))
{
return $this->whereNested(function($query) use ($column)
{
foreach ($column as $key => $value)
{
$query->where($key, '=', $value);
}
}, $boolean);
}
I suggest you do something like this:
我建议你做这样的事情:
$condition = array(
'field_1' => '%value_1%',
'field_2' => '%value_2%'
);
$users = User::where(function($q) use ($condition){
foreach($condition as $key => $value){
$q->where($key, 'LIKE', $value);
}
})->get();