【问题标题】:How can I build a condition based query in Laravel 6.x?如何在 Laravel 6.x 中构建基于条件的查询?
【发布时间】:2020-02-19 01:31:08
【问题描述】:
public function test(Request $request){
    $apartments = DB::table('apartments');
    if ($request->filled('bathrooms')) {
        $apartments->where('bathrooms', '=' ,$request->input('bathrooms'));
    }
    if ($request->filled('rooms_number')) {
        $apartments->where('rooms_number', '=', $request->input('rooms_number'));
    }
    $apartments->get();
    return view('pages.test2' , compact('apartments'));
}

如何翻译这段代码以便在 Laravel 中工作?

【问题讨论】:

  • 这个查询工作正常吗?您期望使用 eloquent 做什么?你能澄清一下吗?
  • 当我将 DB::table('table') 与其余查询分开时,它不会返回结果
  • 最好使用 DB::table('apartments')->where('bathrooms/rooms_number','=',$request->batgrooms/rooms_number)->get() 在你的if 子句并删除第 2,9 行。但是如果您不喜欢干净的代码,我认为您的代码可以工作但不干净。

标签: php laravel


【解决方案1】:

您可以将when 用作conditional clause:

public function test (Request $request)
{
    $apartments = DB::table('apartments')
        ->when($request->filled('bathrooms'), function ($query) use ($request) {
            return $query->where('bathrooms', '=', $request->input('bathrooms'));
        })
        ->when($request->filled('rooms_number'), function ($query) use ($request) {
            return $query->where('rooms_number', '=', $request->input('rooms_number'));
        })
        ->get();

    return view('pages.test2' , compact('apartments'));
}

【讨论】:

  • @folipso 很高兴它有帮助。
猜你喜欢
  • 2012-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-05
  • 2018-04-16
  • 2011-09-29
  • 2020-09-15
相关资源
最近更新 更多