显示通知逻辑

时间:2016-09-07 08:14:53

标签: php laravel notifications social-networking

我正在使用Laravel框架构建社交网络,并且我有一个通知系统。

基本上,只要用户以这5种不同的方式与网站互动:

  1. 用户赞成帖子。
  2. 帖子中的用户评论。
  3. 用户赞成评论。
  4. 用户回复评论。
  5. 用户赞成回复。
  6. 通知被添加到该用户的通知表中(例如,OP(原始海报),如果用户赞成评论,则为拥有该评论的用户添加通知,并且在该通知表中我有这些通知配置。

    $table->string('id')->primary();
            $table->string('type');
            $table->morphs('notifiable');
            $table->text('data');
            $table->timestamp('read_at')->nullable();
            $table->timestamps();
    

    因此,基本上我可以使用命令Auth::user()->unreadNotifications获取每个登录用户的未读通知,该命令是一个包含所有通知信息的数组。

    但这是我的问题。例如,100个用户upvotes OP的一个帖子,这意味着如果我循环通过未读通知数组,我将收到100个通知,但我想要这样的事情,'最后一个与帖子交互的用户'。 'x'人有。 “与您的帖子互动”。

    但是我无法执行它,到目前为止,我已经设法通过使用此逻辑计算用户将看到的通知数量:

    public function get_Notification_Count()
    {
        $total_notifications = Auth::user()->unreadNotifications;
        $num_of_posts = array();
        $num_of_comments = array();
        $num_of_replies = array();
        $num_of_upvoted_comments = array();
        $num_of_upvoted_replies = array();
        // $num_of_notifications = array();
    
        foreach ($total_notifications as $notification) {
            if ($notification->type == 'App\Notifications\UserUpvotedPost') {
                array_push($num_of_posts, $notification->data['post_id']);
                $num_of_posts = array_unique($num_of_posts);
            }
            if ($notification->type == 'App\Notifications\UserCommented') {
                array_push($num_of_comments, $notification->data['post_id']);
                $num_of_comments = array_unique($num_of_comments);
            }
            if ($notification->type == 'App\Notifications\UserReplied') {
                array_push($num_of_replies, $notification->data['comment_id']);
                $num_of_replies = array_unique($num_of_replies);
            }
            if ($notification->type == 'App\Notifications\UserUpvotedComment') {
                array_push($num_of_upvoted_comments, $notification->data['comment_id']);
                $num_of_upvoted_comments = array_unique($num_of_upvoted_comments);
            }
            if ($notification->type == 'App\Notifications\UserUpvotedReply') {
                array_push($num_of_upvoted_replies, $notification->data['reply_id']);
                $num_of_upvoted_replies = array_unique($num_of_upvoted_replies);
            }
        }
    
        $num_of_notifications = count(array_merge($num_of_posts, $num_of_comments, $num_of_replies, $num_of_upvoted_comments, $num_of_upvoted_replies));
    
        return $num_of_notifications;
    }
    

1 个答案:

答案 0 :(得分:3)

我认为您最好的选择是对查询进行分组:

Auth::user()->unreadNotifications()->select(\DB::raw('COUNT(*) as count'), 'type')
->groupBy('type')
->get();

我还没有测试过这个,但是给它一个旋转;)

相关问题