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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程