对Sequelize协会感到困惑

时间:2012-10-29 15:51:11

标签: node.js database-design sequelize.js

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

只需将webapp中的用户和系统通知视为一个非常简单的案例:

  • 该网站有很多用户
  • 该网站会向部分或每个用户发送通知,同一通知只保存为一条记录
  • 用户可以知道他/她收到的任何通知(阅读日期)

然后我按照预期设计了3个表:

  1. Useridname
  2. NotificationidtitlecontentsendAt
  3. NotifyidUserId(作为接收方),NotificationIdreadAt
  4. 我可以通过Sequelize简单地定义UserNotification模型。但我只是不知道如何通过外键NotifyUserId使用关联使NotificationId与2个表相关。

    我尝试使用hasOne这样的关联:

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

    然后在NotifyIdUser表中都有一个Notification列。这不是我的期望。也许我认为使用关联是错误的方式,所以我想知道如何正确使用它?

    此外,如果我想获得结果作为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;
    

1 个答案:

答案 0 :(得分: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);
});
相关问题