2

我正在开发一个相当简单的应用程序,我希望我的用户能够订阅通知。所以系统应该:

  • 当他们订阅的某个事件发生时发送通知。
  • 向他们选择的渠道发送通知(电子邮件或 slack)

下面是每个用户可以订阅的不同通知的示例。

在此处输入图像描述

我想知道如何使用 Laravel 做到这一点。我的第一个想法是:

  1. 在表上创建一个notificationsJSON 列users,并将其存储起来(可能使用管理大量用户设置课程中的知识。)
{
  "todo": {
    "assigned": [
      {
        "email": true,
        "slack": true
      }
    ],
    "mentioned": [
      {
        "email": true,
        "slack": true
      }
    ]
  },
  "project": {
    "created": [
      {
        "email": true,
        "slack": true
      }
    ]
  }
}

但是,我不确定这是否是好的做法。此外,我也不确定如何实际动态发送通知。

为了发送它,我想使用 Laravel 通知系统:

Notification::send($user, new TodoCreated($todo));

我不确定这是否是最好的方法,或者使用事件/侦听器设置是否更有意义?一个

另外,我可以利用类上的via()方法Notification根据用户设置动态指定频道吗?

任何投入将不胜感激。

4

1 回答 1

4

我认为多对多关系更适合这种情况。

Tables:

User
 - id

Notifications
 - id

NotificationUser <-- pivot table
 - notifcation_id
 - user_id
 - channel_id

Channel
 - id
 - name 

要考虑数据透视表中的这些附加字段,请在用户模型关系中定义它们:

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function notifications()
    {
        return $this->belongsToMany(Notification::class)->withPivot(['channel_id']);
    }
}

请参阅:https ://laravel.com/docs/8.x/eloquent-relationships#retrieving-intermediate-table-columns

这样,你可以利用 Laravel (eloquent) 自带的关系方法。

IE:

aUser->notifications(); # Getting a list of a user's notifications
aUser->attach(1, ['channel' => 1]); # attaching a notification to the user

您还可以利用查询范围为用户检索一个通知渠道等

请参阅:https ://laravel.com/docs/8.x/eloquent#query-scopes

然后按照您的计划使用模型/侦听器模式。

于 2021-02-01T10:08:15.700 回答