我正在为移动应用程序构建Restful Api。如果用户在个人资料中将通知设置保存为true,我需要将通知推送给他。
我创建了以下结构:
用户表:
id 名称电子邮件
1测试test@test.com
2 测试1test1@test1.com
通知表:
id 通知名称
1 类似通知
2 注释通知
user_notification表:
id notification_id user_id 值(0=关闭,1=打开)
1 nbsp nbsp nbsp nbsp nbsp;1 nbsp nbsp nbsp nbsp nbsp nbsp 1 nbsp nbsp;0 nbsp
2 nbsp nbsp nbsp nbsp nbsp;2 nbsp nbsp nbsp nbsp nbsp nbsp 1 nbsp nbsp;1 nbsp
3 nbsp nbsp nbsp nbsp nbsp;1 nbsp nbsp nbsp nbsp nbsp nbsp 1 nbsp nbsp;1 nbsp
4 nbsp nbsp nbsp nbsp nbsp;2 nbsp nbsp nbsp nbsp nbsp nbsp 1 nbsp nbsp;1 nbsp
在上面的表结构中,我创建了一个带有额外字段value
的透视表,用于保存用户的设置。
有没有其他很好的方法可以做到这一点,我可以最大限度地减少查询并快速响应
您的数据透视表应该只包含定义的两个引用notification_id
和user_id
。向其中添加更多字段会将其作为数据透视表否定。
您可以将value
字段放在notifications
表上,也许命名它更像is_active
。是你的通知有设置,对吧?因此,设置是在通知上进行的,而不是仅用于连接两个表的透视表。
此外,作为一个建议,按照Laravel中的正常约定,将您的数据透视表按字母顺序排列(请参阅文档)
在User.php
模型中,添加关系
public function notifications() {
return $this->hasMany(App'Notification::class, 'notification_user');
}
当查询此关系时,您所要做的就是:
foreach($user->notifications as $notification) {
if($notification->is_active) {
// do something
}
}