2014-10-10 85 views
0

我有以下表格:Laravel - 集團通過同日(週一,週二,ETCC)

TABLE:schedule 

id day name 
----------------------------- 
1 Mon test 
2 Mon hello 
3 Tue another 
4 Tue here 
5 Wed go 

我對此有一個Laravel模型,所以我想 這裏組一天是結果我想有作爲對象:

['Mon']-> array[0]='name'=>test, 
     array[1]='name'=>hello, 
['Tue']-> array[0]='name'=>another, 
     array[1]='name'=>here, 

這裏是我在HomeController的代碼:

$schedule = DB::table('schedule') 
      ->select('*') 
      ->groupBy('day') 
      ->get(); 

這不是w^orking只顯示一天而不是將它們分組,任何人都知道爲什麼?

謝謝

回答

0

這是一個有點複雜的問題。我想,你正在尋找類似如下:

$schedules = DB::table('schedule') 
       ->selectRaw('id, day, group_concat(name) as name') 
       ->groupBy('day') 
       ->get(); 

    $data = array(); 

    foreach ($schedules as $schedule) { 
     $data[$schedule->day][] = explode(",",$schedule->name); 
    } 

    var_dump($data); 

輸出:

array (size=3) 
    'Mon' => 
    array (size=1) 
     0 => 
     array (size=12) 
      0 => string 'test' (length=4) 
      1 => string 'hello' (length=5) 
    'Tue' => 
    array (size=1) 
     0 => 
     array (size=3) 
      0 => string 'another' (length=6) 
      1 => string 'here' (length=4) 
    'Wed' => 
    array (size=1) 
     0 => 
     array (size=1) 
      0 => string 'go' (length=2) 

編輯:

另做group_concat額外的領域。

$schedules = DB::table('schedule') 
       ->selectRaw('id, day, group_concat(name) as name, group_concat(city) as city') 
       ->groupBy('day') 
       ->get(); 

    $data = array(); 

    foreach ($schedules as $schedule) { 
     $data[$schedule->day]['name'] = explode(",",$schedule->name); 
     $data[$schedule->day]['city'] = explode(",",$schedule->city); 
    } 

    var_dump($data); 
+0

怎麼樣,如果我有另外的名字更多的列,如:時間,地點,城市如何將我做 – user3150060 2014-10-10 04:58:05

+0

CONCAT的「」是n要一個很好的解決方案,因爲我可以有「」在我的名字,地址或城市列? – user3150060 2014-10-10 05:05:51

+0

然後你不能在你的查詢中進行分組。你有使用PHP做。 – Anam 2014-10-10 05:09:44

相關問題