显示通知逻辑


Displaying Notifications Logic

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

基本上,每当用户以以下5种不同的方式与网站交互时:

  1. 用户对帖子投了赞成票。
  2. 帖子中的用户评论。
  3. 用户对评论投了赞成票。
  4. 用户回复评论。
  5. 用户对回复投了赞成票。
通知将添加到该用户的通知表中(

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 个用户对 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;
}

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

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

我还没有测试过这个,但试一试;)