我正在从数据库中检索项目并按“月份”对它们进行分组:
$events = DB::table('events')->get();
$events_by_month = $events->groupBy('month');
这会返回一个像这样的集合:
Collection {#186 ▼
#items: array:1 [▼
"DEC" => Collection {#159 ▼
#items: array:1 [▼
0 => {#166 ▼
// attributes
}
]
},
"JAN" => Collection {#159 ▼
#items: array:1 [▼
0 => {#166 ▼
// attributes
}
]
}
]
}
我将其传递到我想要显示给定月份的项目的 View 。我可以在这里使用 whereIn
(哪种情况下关键是什么?)或者还有其他/更好的方法吗?
whereIn
中没有键返回错误:
@foreach($mths->whereIn(['DEC', 'JAN']) as $mth => $events)
最佳答案
$events_by_month=DB::table('events')->get()->groupBy('month');
在 View 中:
@foreach($events_by_month->where(['month'=>'DEC') as $month=>$events)
{{ $month }}
@foreach($events as $event)
{{ $event }}
@endforeach
@endforeach
关于php - Laravel 集合 : GroupBy items and use WhereIn in the view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39880706/