【问题标题】:Laravel: search and filter dataLaravel:搜索和过滤数据
【发布时间】:2021-06-06 20:38:10
【问题描述】:

我想在 laravel 中对数据进行多重过滤,但我显示此错误:

Too few arguments to function Illuminate\Support\Collection::get()

请帮我解决这个问题。

public function searchLanding(Request $request)
{

    $landings = Landing::all();

    if(count($landings) && !is_null($request->title)) {
        $landings = $landings->where("name", "LIKE", "%{$request->title}%")->get();
    }

    if (count($landings) && !is_null($request->start_at)) {
        $landings = $landings->where('start_at', '>=', $request->start_at)->get();
    }

    if (count($landings) && !is_null($request->end_at)) {
        $landings = $landings->where('end_at', '<=', $request->end_at)->get();
    }

}

【问题讨论】:

    标签: php laravel eloquent laravel-controller


    【解决方案1】:
    public function searchLanding(Request $request)
    {
    
        $landings = Landing::query();
    
        if(!is_null($request->title)) {
            $landings->orWhere("name", "LIKE", "%{$request->title}%");
        }
    
        if (!is_null($request->start_at)) {
            $landings->orWhere('start_at', '>=', $request->start_at);
        }
    
        if (!is_null($request->end_at)) {
            $landings->orWhere('end_at', '<=', $request->end_at);
        }
    
         return $landings->get();
    }
    

    注意:
    当您仍在构建查询时,不应调用 all()get(),仅在您想要获得结果时调用它们。

    如果您希望所有条件都为真,请使用where()
    或当您希望其中一个条件为真时使用orWhere()

    在上面的示例中,只有一个条件需要为真,例如在titlestart_at 之后或end_at 之前搜索。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      • 2017-05-29
      • 2019-01-04
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多