Laravel groupBy 无法正常工作

Laravel groupBy not working properly

我想根据我的习惯做一组condition.But我不确定我的方法是否正确。

我的代码

$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))

由于 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();

使用 when 条件子句(来自 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();