1
我刚刚发现Sequelize是一个很好的ORM框架,可以在我的节点+ MySQL webapp中使用。但是当我设计我的数据库表时,我对Sequelize关联感到困惑。对Sequelize协会感到困惑
试想一下用户和系统通知在web应用程序是一个非常简单的例子:
- 该网站拥有众多用户
- 该网站会发送通知给一些或所有的用户,同样的通知刚保存为一个记录
- 用户可以知道他/她收到读或不(通过读取日期)
然后我设计的3代表作为指望任何通知:
User
:id
,name
Notification
:id
,title
,content
,sendAt
Notify
:id
,UserId
(如接收器),NotificationId
,readAt
我可以简单地定义User
和Notification
月由Sequelize提供。但我只是不知道如何使用关联来使Notify
与2个表相关,通过外键UserId
和NotificationId
。
我曾尝试使用hasOne
协会这样的:
Notify.hasOne(User);
Notify.hasOne(Notification);
然后有两个User
和Notification
表中而来的,是NotifyId
列。这不是我的期望。也许我认为使用关联的方法不对,所以我想知道如何正确使用它?
此外,如果我想要得到的结果作为JSON:
[
{id: 123, user: [Object some user], notification: [Object some notification], readAt: null},
{id: 124, user: [Object another user], notification: [Object some notification], readAt: "Mon Oct 29 2012 20:44:54 GMT+0800"}
]
我怎么能在我之前使用的SQL使用find
方法查询只有一次这样的:
SELECT
Notify.id as 'Notify.id',
User.name as 'User.name',
Notification.title as 'Notification.title',
Notification.sendAt as 'Notification.sendAt',
Notify.readAt as 'Notify.readAt'
FROM User, Notification, Notify
WHERE
Notify.UserId = User.id AND
Notify.NotificationId = Notification.id;
“然后在User和Notification表中都有一个NotifyId列,这不像我期望的那样。”你想怎么样,对不起? –
我希望在用户和通知表中都不应该存在NotifyId。 – mytharcher