Laravel - 为不同渠道的每个用户存储通知设置
Laravel - Storing notification settings per user with different channels
我正在开发一个相当简单的应用程序,我希望我的用户能够在其中订阅通知。所以系统应该:
- 当他们订阅的特定事件发生时发送通知。
- 向他们选择的渠道(电子邮件或 slack)发送通知
下面是每个用户可以订阅的不同通知的示例。
我想知道如何使用 Laravel 执行此操作。我的第一个想法是:
- 在
users
table 上创建一个 notifications
JSON 列,并像这样存储它(可能使用从 Managing Mass User Settings 课程中学到的知识。)
{
"todo": {
"assigned": [
{
"email": true,
"slack": true
}
],
"mentioned": [
{
"email": true,
"slack": true
}
]
},
"project": {
"created": [
{
"email": true,
"slack": true
}
]
}
}
但是,我不确定这是否是好的做法。此外,我也不确定如何实际动态发送通知。
发送出去,我想用Laravel的通知系统:
Notification::send($user, new TodoCreated($todo));
我不确定这是不是最好的方法,或者使用 Event/Listener 设置是否更有意义? A
还有,我可以利用Notification
class上的via()
方法,根据用户设置动态指定频道吗?
如有任何意见,我们将不胜感激。
我认为多对多关系更适合这种情况。
Tables:
User
- id
Notifications
- id
NotificationUser <-- pivot table
- notifcation_id
- user_id
- channel_id
Channel
- id
- name
要在数据透视表 table 中考虑这些附加字段,请在用户模型关系中定义它们:
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) 附带的关系方法。
即:
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
然后按照您的计划使用 model/listener 模式。
我正在开发一个相当简单的应用程序,我希望我的用户能够在其中订阅通知。所以系统应该:
- 当他们订阅的特定事件发生时发送通知。
- 向他们选择的渠道(电子邮件或 slack)发送通知
下面是每个用户可以订阅的不同通知的示例。
我想知道如何使用 Laravel 执行此操作。我的第一个想法是:
- 在
users
table 上创建一个notifications
JSON 列,并像这样存储它(可能使用从 Managing Mass User Settings 课程中学到的知识。)
{
"todo": {
"assigned": [
{
"email": true,
"slack": true
}
],
"mentioned": [
{
"email": true,
"slack": true
}
]
},
"project": {
"created": [
{
"email": true,
"slack": true
}
]
}
}
但是,我不确定这是否是好的做法。此外,我也不确定如何实际动态发送通知。
发送出去,我想用Laravel的通知系统:
Notification::send($user, new TodoCreated($todo));
我不确定这是不是最好的方法,或者使用 Event/Listener 设置是否更有意义? A
还有,我可以利用Notification
class上的via()
方法,根据用户设置动态指定频道吗?
如有任何意见,我们将不胜感激。
我认为多对多关系更适合这种情况。
Tables:
User
- id
Notifications
- id
NotificationUser <-- pivot table
- notifcation_id
- user_id
- channel_id
Channel
- id
- name
要在数据透视表 table 中考虑这些附加字段,请在用户模型关系中定义它们:
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) 附带的关系方法。
即:
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
然后按照您的计划使用 model/listener 模式。