我有下表:
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();
这不仅仅显示一天而且没有分组,有谁知道为什么?
由于
答案 0 :(得分: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);