2012-10-29 52 views
1

我刚刚发现Sequelize是一个很好的ORM框架,可以在我的节点+ MySQL webapp中使用。但是当我设计我的数据库表时,我对Sequelize关联感到困惑。对Sequelize协会感到困惑

试想一下用户和系统通知在web应用程序是一个非常简单的例子:

  • 该网站拥有众多用户
  • 该网站会发送通知给一些或所有的用户,同样的通知刚保存为一个记录
  • 用户可以知道他/她收到读或不(通过读取日期)

然后我设计的3代表作为指望任何通知:

  1. Useridname
  2. NotificationidtitlecontentsendAt
  3. NotifyidUserId(如接收器),NotificationIdreadAt

我可以简单地定义UserNotification月由Sequelize提供。但我只是不知道如何使用关联来使Notify与2个表相关,通过外键UserIdNotificationId

我曾尝试使用hasOne协会这样的:

Notify.hasOne(User); 
Notify.hasOne(Notification); 

然后有两个UserNotification表中而来的,是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; 
+0

“然后在User和Notification表中都有一个NotifyId列,这不像我期望的那样。”你想怎么样,对不起? –

+0

我希望在用户和通知表中都不应该存在NotifyId。 – mytharcher

回答

3

而且我发现正确的方法。我意识到我的Notify表是一个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); 
});