【问题标题】:Group similar notifications in Laravel/Eloquent在 Laravel/Eloquent 中对类似的通知进行分组
【发布时间】:2015-09-15 00:29:52
【问题描述】:

我的通知表如下所示

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 个单独的通知说他们的帖子已被喜欢。

提前致谢!

【问题讨论】:

    标签: php mysql notifications laravel-5 eloquent


    【解决方案1】:

    如果你只是按一维分组,你可以在结果集合上使用groupBy(),例如:

    $grouped_notifs = $notifs->groupBy('from_type');
    

    这会给你一个数组的集合。然后,您可以循环并输出计数 > 1 的数组的聚合数据。

    听起来您可能想同时按from_type 和to_type 进行分组。为了实现这一点,您可以通过将每个数组从 $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 中,那么这应该可以工作。

    【讨论】:

      猜你喜欢
      • 2019-08-06
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 2018-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多