laravel 中使用条件查询的时候,会根据不同的情况使用不同的条件查询


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,如果是假,则执行默认的方法


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM