[英]Laravel 4: optional wherein clause
基本上,我在 Laravel 中有一个路由系统,它传递一个可选的高级标签名称,该名称用于从数据库集合(我正在使用 MongoDB)中检索标签列表,并依次使用该标签列表从另一个集合中检索数据。
我的控制器:
public function index($tag){
$tags = array();
if ($tag){
//get an array of tags from db
}
$data = DB::collection('notices')
->whereIn("tags", $tags //<-- an array of tags)
->GET(...);
}
现在,当我确实给出了一个标记并且有一个数组要传递给 whereIn 子句时,就会按预期检索数据。 但是,如果未给出参数,则查询将返回错误,因为没有可查询的内容。
因此,我需要知道在 Laravel 中是否有可能使 ->whereIn 以某种方式可选或为其提供一个数组,以便查询就像没有 where 子句一样
这就是您要寻找的:
public function index($tag){
$tags = array();
$data = DB::collection('notices');
if ($tag){
//get an array of tags from db
$data->whereIn("tags", $tags //<-- an array of tags)
}
$data->get(...);
}
在 Laravel 5+ 中,您可以使用“条件条款”: https ://laravel.com/docs/5.3/queries#conditional-clauses
$role = $request->input('role');
$users = DB::table('users')
->when($role, function ($query) use ($role) {
return $query->where('role_id', $role);
})
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.