对Sequelize协会感到困惑
我刚刚发现Sequelize是一个很好的ORM框架,可以在我的节点+ MySQL webapp中使用。 但是当我devise我的数据库表时,我对Sequelize关联感到困惑。
只要想一想,webapp中的用户和系统通知就是一个非常简单的例子:
- 该网站有许多用户
- 该网站会向一些或每个用户发送通知,并且相同的通知只保存为一条logging
- 用户可以知道他/她收到的任何通知是否被读取(通过读取date)
然后我devise了3个表格:
-
User
:id
,name
-
Notification
:id
,title
,content
,sendAt
-
Notify
:id
,UserId
(作为接收者),NotificationId
,readAt
我可以简单地通过Sequelize定义User
和Notification
模型。 但是我只是不知道如何使用关联使Notify
与这两个表相关,通过外键UserId
和NotificationId
。
我试图使用这样的hasOne
关联:
Notify.hasOne(User); Notify.hasOne(Notification);
然后在User
和Notification
表中都有一个NotifyId
列。 这不是我的期望。 也许我认为使用关联的方式是错误的,所以我想知道如何正确使用它?
另外,如果我想以JSON的forms获得结果:
[ {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"} ]
我如何才能使用find
方法查询只是一次像我以前使用的SQL:
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;
我find了正确的方法。 我意识到我的通知表是一个entiry表,因为包含一个readAt
列。 所以协会应该被定义为:
Notification.hasMany(db.Notify); User.hasMany(db.Notify);
那么一切都变好了。
find
的第二个问题也解决了。 就像这样使用:
Notify.findAll({ include: ['User', 'Notification'] }).success(function (notify) { console.log(notify.user); console.log(notify.notification); });