doutuo6689 2014-09-05 19:41
浏览 30
已采纳

有没有办法建立一个基于雄辩的输入参数的查询?

To explain this question better I'll just give an example:

Let's say I have a world records database and wish to create an api for it. Let's say I want to add a search route that takes in GET or POST parameters (let's keep it simple and just say GET for now). Is it possible to write a search controller method which uses something like an array as a parameter to Eloquent's where method while also utilizing a like parameter (MySQL LIKE)?

I have the following which works but only for exact values:

public function search()
{

    $params = Input::all();

    return Records::where($params)->get();

}
  • 写回答

1条回答 默认 最新

  • dongzhan1383 2014-09-05 19:45
    关注

    You should be able to:

    public function search()
    {
        $params = Input::all();
    
        $query = Records::newQuery();
    
        foreach($params as $key => $value)
        {
           $query->where($key, 'LIKE', "%$value%")
        }
    
        return $query->get();
    }
    

    In the context of a scope, you can get fancier:

    class User extends Eloquent {
    
        public function scopeFilter($query, $input = null)
        {
            $input = $input ?: Input::all();
    
            foreach($input as $key => $value)
            {
                if (Schema::hasColumn($this->getTable(), $key))
                {
                    $query->where($key, 'LIKE', "%$value%")
                }
            }
    
            return $query;
        }
    
    }
    

    Then you can do:

    $filtered = User::filter()->get();
    

    Or

    $filtered = User::filter(Input::only('name', 'age'))->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?