我可以使用laravel数据库查询的条件吗?

时间:2019-06-15 18:52:20

标签: mysql laravel laravel-5 eloquent laravel-query-builder

我可以在查询中使用if条件吗,我想在$request->review = 7显示7天数据而其他条件为默认30天数据时使用过滤器。

$reviews = Review::orderBy('created_at', 'DESC')
    ->orWhere('created_at', '>=', if($request->review == "7"){ $month = 7 })
    ->where('listing_id', $id)
    ->where('user_id', Auth::User()->id)
    ->paginate(6, ['*'], 'review');

4 个答案:

答案 0 :(得分:1)

您可以使用类似这样的内容:

$reviews = Review::orderBy('created_at', 'DESC')
    ->orWhere('created_at','>=',now()->subDays($request->review == 7 ? 7 : 30)
    ->where('listing_id', $id)
    ->where('user_id', Auth::user()->id)
    ->paginate(6, ['*'], 'review');

但是请记住,您仍然可能得到错误的结果。

您应该确保将括号添加到查询中的正确位置,否则您可能会得到其他用户的结果,因此实际上您很可能想使用类似这样的内容:

$reviews = Review::orderBy('created_at', 'DESC')
    ->where(function($q) use ($request) {
      $q->where('listing_id', $id)
         ->orWhere('created_at','>=',now()->subDays($request->review == 7 ? 7 : 30)
    })
    ->where('user_id', Auth::user()->id)
    ->paginate(6, ['*'], 'review');

但是您还没有解释要从数据库中获得什么确切结果,因此只是一个提示。

答案 1 :(得分:0)

您可以按光标分割Eloquent Builder。

$cursor = Review::orderByDesc('created_at');

if ($request->review == "7") {
    $cursor->orWhere('created_at','>=', 7));
}
$reviews = $cursor->where('listing_id', $id)
    ->where('user_id', Auth::user()->id)
    ->paginate(6, ['*'], 'review');

答案 2 :(得分:0)

$reviews = Review::where('listing_id', $id)
                 ->where('user_id', Auth::user()->id);

if($request->review == 7){
    $reviews->Where('created_at','>=',now()->subDays($request->review));
}

if($request->review != 7){
    $reviews->Where('created_at','>=',now()->subDays(30));
}

$reviews->orderBy('created_at', 'DESC')
        ->paginate(6, ['*'], 'review');

理解了以上内容之后,您可以像下面一样使用三元运算符简化上面的内容。

$reviews = Review::where('listing_id', $id)
    ->where('user_id', Auth::user()->id);
    ->Where('created_at','>=',now()->subDays(($request->review == 7)? 7 : 30));
    ->orderBy('created_at', 'DESC')
    ->paginate(6, ['*'], 'review');

答案 3 :(得分:0)

$ reviews = Review :: orderBy('created_at','DESC');

if($ request-> review ==“ 7”){

$reviews->orWhere('created_at','>=', 7));

}    $ reviews = $ reviews-> where('listing_id',$ id)

->where('user_id', Auth::User()->id)

->paginate(6, ['*'], 'review');