简体   繁体   English

Laravel 4:可选的 where 子句

[英]Laravel 4: optional wherein clause

Basically I have a routing system in Laravel that passes on an optional high level tag name which is used to retrieve a list of tags from a database collection (I am using MongoDB) and use that tag list in turn to retrieve data from another collection.基本上,我在 Laravel 中有一个路由系统,它传递一个可选的高级标签名称,该名称用于从数据库集合(我正在使用 MongoDB)中检索标签列表,并依次使用该标签列表从另一个集合中检索数据。

My Controller:我的控制器:

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(...);
}

Now when I do give a tag and there is an array to pass on to the whereIn clause then the data is retrieved as expected.现在,当我确实给出了一个标记并且有一个数组要传递给 whereIn 子句时,就会按预期检索数据。 However if parameter is not give then the query returns an error as there is nothing to query with.但是,如果未给出参数,则查询将返回错误,因为没有可查询的内容。

As such I need to know whether it is possible in Laravel to either make the ->whereIn optional somehow or give an array to it so the query acts as if there is no where clause因此,我需要知道在 Laravel 中是否有可能使 ->whereIn 以某种方式可选或为其提供一个数组,以便查询就像没有 where 子句一样

That's what you're looking for: 这就是您要寻找的:

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(...);
}

In Laravel 5+ you can use "Conditional Clauses": https://laravel.com/docs/5.3/queries#conditional-clauses在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM