我想依靠我的自定义条件制作一个小组。但我不确定我的方式是否正确。
我的代码
$cderList = $cderListQuery->groupBy('cder_id')
->groupBy('name')
->groupBy(function ($query) {
if(!is_null($this->hp) || !is_null($this->hp))
{
$query->groupBy('Value_Float');
}
})
->orderBy('introduced', 'DESC')
->limit(20)
->get();
错误详情
strtolower() expects parameter 1 to be string, object given
in Grammar.php (line 58)
at HandleExceptions->handleError(2, 'strtolower()
expects parameter 1 to be string, object given',
'/home/vendor/laravel/
framework/src/Illuminate/Database/Grammar.php',
58, array('value' => object(Closure), 'prefixAlias' => false))
答案 0 :(得分:2)
由于orderBy
不喜欢闭包,你可以将查询分解为:
$query = $cderListQuery->groupBy('cder_id')
->groupBy('name');
if(!is_null($this->hp) || !is_null($this->hp))
{
$query->groupBy('Value_Float');
}
$cderList = $query->orderBy('introduced', 'DESC')
->limit(20)
->get();
答案 1 :(得分:0)
使用when Conditional子句(来自laravel文档) 我猜你想要做的是按照' Value_Float'只有条件成立时
//Set the condition here
$condition = !is_null($this->hp) || !is_null($this->hp);
$cderList = $cderListQuery->groupBy('cder_id')
->groupBy('name')
->when($condition, function($query){
//This segment will only run if condition is true
return $query->groupBy('Value_Float');
})
->orderBy('introduced', 'DESC')
->limit(20)
->get();