Laravel条件有雄辩的地方

时间:2018-10-11 12:05:48

标签: laravel

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

// test.css
.someClass {
  background: #000;
  color: #000;
}


// test.js
const el = document.getElementById('someEl');
el.classList.add('someClass');
// ...
el.classList.remove('someClass');

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

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

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

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);   
   }
}

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

2 个答案:

答案 0 :(得分:3)

使用import org.apache.spark.sql.expressions.Window val w = Window.partitionBy($"ap",$"station",$"bucket"). orderBy(unix_timestamp($"time")). rangeBetween(Long.MinValue, -1) val df = input_data.withColumn("shouldPrintMessage",when(max($"rssi".over(w))>$"rssi",true)) 函数提供条件,以获得更好的代码风格,例如see more

when

答案 1 :(得分:1)

Laravel提供when(),它允许您在条件成功时运行闭包,该闭环可用于链接:

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

尽管如此,我认为在这种情况下不链接所有内容会更简单,尤其是当您的条件变得更加复杂时:

$query = Offer::where('published', true) 
   ->orderBy('created_at','desc');

if ($person) {
    $query->where('person',$person);
}

return $query->paginate(9);

我认为您在函数中也缺少一个return调用,我在后面的示例中添加了该函数。

相关问题