Laravel group不能正常工作

时间:2017-09-14 12:06:03

标签: php laravel laravel-5 laravel-4 laravel-5.3

我想依靠我的自定义条件制作一个小组。但我不确定我的方式是否正确。

我的代码

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

2 个答案:

答案 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();