Laravel条件有雄辩的地方 [英] Laravel conditional where with eloquent

查看:51
本文介绍了Laravel条件有雄辩的地方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有传递简单参数的基本功能:

I've got basic function that I'm passing simple parameter:

public function template($person)
{
      $offers = Offer::where([
          ['person', $person],
          ['published', true],
      ])
      ->orderBy('created_at','desc')->paginate(9);   
 }

现在我想让它具有条件性,如果没有参数的话:

now I want to make it confitional, if there is a parameter or not:

public function template($person)
{
   if ($person) {
      $offers = Offer::where([
          ['person', $person],
          ['published', true],
      ])
      ->orderBy('created_at','desc')->paginate(9);   
   } else {
      $offers = Offer::where([
          ['published', true],
      ])
      ->orderBy('created_at','desc')->paginate(9);   
   }
}

这可行,但这不是一个好习惯,如果我将有更多参数怎么办?

this works, but it is not a good practice, what if I will have more parameters:

public function template($person, $country, $region) {
  ....
}

然后我将不得不提出多个案例.有口才使它更简单的辅助功能吗?

Then I would have to make multiple cases. Is there any helper function for eloquent to make it simpler?

推荐答案

使用 when 函数获得更好的代码样式的条件,例如

use when function for condition for better code sytle like this see more

$offers = Offer::when($person,function($query,$person) {
        return $query->where('person',$person);
})->where('published', true)
      ->orderBy('created_at','desc')->paginate(9); 

这篇关于Laravel条件有雄辩的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆