[英]Group similar notifications in Laravel/Eloquent
我的通知表如下所示
id (eg. 1) | from_id (eg. 1) | from_type (eg. liked) | to_id (eg. 2) | to_type (comment) | item_id (eg. 1) | read (0 or 1) | created_at | updated_at
目前,當我在Laravel中獲取通知時,我會撥打此電話
$notifs = Notification::with('from')
->where("to_id", "=", $user_id)
->where("read", "=", 0)
->limit(40)
->get();
這非常完美,除了我決定繼續按類型對通知進行分組,以便用戶可以獲得“ 13個人喜歡您的帖子”,而不是13個單獨的通知表明他們的帖子已被喜歡。
提前致謝!
如果僅按一個維度分組,則可以在結果集合上使用groupBy()
,例如:
$grouped_notifs = $notifs->groupBy('from_type');
這將為您提供數組的集合。 然后,您可以遍歷並輸出計數> 1的陣列的匯總數據。
聽起來您可能想同時按from_type
和to_type
進行分組。 為此,您可以通過將$grouped_notifs
每個數組$grouped_notifs
為一個集合並在其中運行groupBy()
過濾器來增加一層。
foreach( $grouped_notifs as $from_type_group ) {
if( count($from_type_group) === 1 ) {
// just output $from_type_group[0] since there's just one
}
else {
// This group has more than one item
$to_type_groups = collect($from_type_group)->groupBy('to_type');
foreach( $to_type_groups as $to_type_group ) {
if( count($to_type_group) === 1 ) {
// output $to_type_group[0]
}
else {
// Output aggregate based on from_type, to_type, and count()
}
}
}
}
從性能角度來看,最好制作一個對所有內容進行適當分組的數據庫查詢,但是如果要將其保留在Eloquent中,則應該可以。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.