我有一个过滤项目的表格:
我正在 Laravel 5.3 中寻找类似的东西:
// some variables get from request()->input('...')
$mode = ['A'];
$type = ['a', 'b'];
$group = [0, 1];
// desirable query
$results = Item::whereIn([
['mode_id', $mode],
['type_id', $type],
['group_id', $group]
])->paginate(10);
我可以做到这一点
$results = Item::whereIn('mode_id', $mode)
->whereIn('type_id', $type)
->whereIn('group_id', $group)
->paginate(10);
但这不是一种动态的方式。例如,如果用户在模式中未选择任何内容,则查询将返回一个空数组。
我们可以使用条件从句:
$results = Item::
when(!empty($mode), function ($query) use ($mode) {
return $query->where('mode_id', $mode);
})
->when(!empty($type), function ($query) use ($type) {
return $query->where('type_id', $type);
})
->when(!empty($group), function ($query) use ($group) {
return $query->where('group_id', $group);
})
->paginate(10);
你可以这样做:
$qb = Item::newQuery();
if (!empty($mode))
{
$qb->whereIn('mode_id', $mode);
}
if (!empty($type))
{
$qb->whereIn('type_id', $type);
}
if (!empty($group))
{
$qb->whereIn('group_id', $group);
}
$results = $qb->paginate(10);
或者在传递之前构建你的 whereIn 关联数组,不包含空的 where's 。
我们可以使用 array_filter 删除所有错误值:
$where = array_filter([
'mode_id' => $mode,
'type_id' => $type,
'group_id' => $group
]);
$results = Item::where($where)->paginate(10);