laravel5.5新出了一個簡便方法when($arg,fun1[,fun2])。當$arg為真的時候,執行閉包fun1,否則執行fun2(可選)
1 $myconsumption = $transaction->selectRaw('business_name,business_id,sum(paid) as account,count(*) as times') 2 ->where('membership_openid', '=', $wxOpenId)//當前用戶微信ID
3 ->where('start_time', '>=', $start_time)//當前月的開始時間
4 ->where('start_time', '<=', $end_time)//當前月的最后時間
5 ->where('status', '=', 1)//交易類型成功的時候
6 ->groupBy('business_name','business_id')//根據商戶名稱,id分組(商戶名稱與商戶ID一一對應)
7 ->when($params['type'] == 1,function ($query){ 8 $query->orderBy('account', 'desc')->orderBy('times', 'desc');//當type為1的時候 則排序為金額,次數 9 },function ($query){ 10 $query->orderBy('times', 'desc')->orderBy('account', 'desc');//當type為2的時候 則排序為次數,金額 11 }) 12 ->limit(5) 13 ->get();
源碼路徑:vendor\laravel\framework\src\Illuminate\Database\Concerns\BuildsQueries.php
/**
* Apply the callback's query changes if the given "value" is true.
*
* @param mixed $value
* @param callable $callback
* @param callable $default
* @return mixed
*/
public function when($value, $callback, $default = null)
{
if ($value) {
return $callback($this, $value) ?: $this;
} elseif ($default) {
return $default($this, $value) ?: $this;
}
return $this;
}
分析源碼可以得出:when會判斷第一個參數的真與假,如果是真,則執行第一個callback,如果是假,則執行默認的方法