我想根据从 json 对象收集的搜索参数构建一系列 Eloquent WHERE 子句。
是这样的(不用管object的语法,,只是为了演示的一种解释):
$searchmap = "
{
"color": "red",
"height": "1",
"width": "2",
"weight": "",
"size": "",
}";
然后我获取对象并解码以获得搜索数组...
$search = json_decode($searchmap, true);
如果我的体重和尺寸设置为 null 或者是一个“空字符串”,我将拥有如下所示的 Eloquent 代码..
$gadgets = Gadget::where('color', '=', $search['color'])
->where('height', '=', $search['height'])
->where('width', '=', $search['width'])
->paginate(9);
如果它们有一个值,那么 Eloquent 代码将如下所示..
$gadgets = Gadget::where('color', '=', $search['color'])
->where('height', '=', $search['height'])
->where('width', '=', $search['width'])
->where('weight', '=', $search['weight'])
->where('size', '=', $search['size'])
->paginate(9);
有没有办法动态地完成这个。
我想问题应该是有没有一种方法可以根据给定参数动态地链接 Eloquent where 子句?
在伪上下文中,我希望做这样的事情
$gadgets = Gadget::
foreach ($search as $key => $parameter) {
if ( $parameter <> '' ) {
->where($key, '=', $parameter)
}
}
->paginate(9);
能否以类似于此的方式创建 where 子句的链接?
感谢您抽出宝贵的时间来看这个!
更新:
我也想出了类似这样的方法,看起来效果不错,但如果改进是个好主意,我欢迎提出建议。
$gadgets = New Gadget();
foreach ($search as $key => $parameter) {
if($parameter != ''){
$gadgets = $gadgets->where($key, '=', $parameter);
}
}
$gadgets = $gadgets->paginate(9);
最终版
感谢下面的@lukasgeiter,我想我会接受这个
$gadgets = Gadget::whereNested(function($query) use ($search) {
foreach ($search as $key => $value)
{
if($value != ''){
$query->where($key, '=', $value);
}
}
}, 'and');
$gadgets = $gadgets->paginate(9);
最佳答案
这很简单。 Laravel 的 where
函数允许你传入一个键值对数组。
$searchmap = array(
'color' => 'red',
'height' => '1'
// etc
);
$gadgets = Gadget::where($searchmap)->paginate(9);
如果你很好奇,那就是源代码的相关部分 (\Illuminate\Database\Query\Builder
)
public function where($column, $operator = null, $value = null, $boolean = 'and')
{
// If the column is an array, we will assume it is an array of key-value pairs
// and can add them each as a where clause. We will maintain the boolean we
// received when the method was called and pass it into the nested where.
if (is_array($column))
{
return $this->whereNested(function($query) use ($column)
{
foreach ($column as $key => $value)
{
$query->where($key, '=', $value);
}
}, $boolean);
}
// many more lines of code....
}
编辑
为了更好地控制它(例如,将“=”更改为另一个比较运算符)尝试使用 laravel 直接在内部使用的代码:
$gadgets = Gadget::whereNested(function($query) use ($searchmap)
{
foreach ($searchmap as $key => $value)
{
if($value != ''){
$query->where($key, '=', $value);
}
}
}, 'and')->paginate(9);
关于php - Laravel - 根据动态参数扩展 Eloquent where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26682817/