2017-09-14 169 views
0

我想根據自己的習慣製作一個小組,但我不知道我的方法是否正確。Laravel groupBy not working properly

我的代碼

$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

這會返回什麼錯誤? – wbail

+0

錯誤詳細信息已更新@wbail – testgo

+0

看起來像問題在此orderBy()子句 –

回答

0

使用當條件從句(來自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(); 
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(); 
相關問題