如何保存用户的通知laravel5和mysql

时间:2015-11-25 10:25:20

标签: php mysql optimization laravel-5.1

我正在为移动应用程序构建Restful Api。如果用户在他的个人资料中将通知设置保存为true,我需要将通知推送给用户。

我创建了以下结构:

用户表:

id name email

1 测试 test@test.com

2 Test1 test1@test1.com

通知表:

id notification_name

1 喜欢通知

2 评论通知

user_notification表:

id notification_id user_id value(0 = off,1 = on)

1 1 1 0

2 2 1 1

3 1 1 1

4 2 1 1

在上面的表结构中,我创建了一个带有额外字段value的数据透视表,用于保存用户的设置。

还有其他很好的方法可以做到这一点,我可以最大限度地减少查询并快速响应

1 个答案:

答案 0 :(得分:1)

您的数据透视表只应包含已定义的两个引用notification_iduser_id。添加更多字段会使其无法作为数据透视表。

您shpuld将value字段放在notifications表上,或者更好地命名为is_active。这是您的通知设置,对吗?因此,设置继续进行通知是有意义的,而不是仅用于连接两个表的数据透视表。

另外,作为一个消息,按照Laravel(see the docs

中的常规惯例,按字母顺序排列数据透视表

User.php模型中,添加关系

public function notifications() {
    return $this->hasMany(App\Notification::class, 'notification_user');
}

在查询这种关系时,您所要做的就是:

foreach($user->notifications as $notification) {
    if($notification->is_active) {
        // do something
    }
}