Confused about Sequelize associations

喜夏-厌秋 提交于 2021-02-08 06:57:25

问题


I just found Sequelize as a good ORM framework to use in my node + MySQL webapp. But when I was designing my database tables, I got so confused about Sequelize associations.

Just think about user and system notification in a webapp as a very simple case:

  • The site has many users
  • The site would send notifications to some or every users, and the same notification just save as one record
  • Users could know any notification he/she received is read or not(by a read date)

Then I design 3 tables as expect:

  1. User: id, name
  2. Notification: id, title, content, sendAt
  3. Notify: id, UserId(as receiver), NotificationId, readAt

I can simply define User and Notification models by Sequelize. But I just don't know how to use associations to make Notify relate to the 2 tables, by foreign key UserId and NotificationId.

I have tried to use hasOne associations like this:

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

Then there comes a NotifyId column in both User and Notification tables. And this is not as my expect. Maybe I thought a wrong way to use associations, so I wanna know how to use it correctly?

Additionally, if I want to get results as the 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"}
]

how can I use find method query just once like in a SQL I used before:

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:


And I found right way. I realized that my Notify table is a entiry table because containing a readAt column. So the association should be defined as:

Notification.hasMany(db.Notify);
User.hasMany(db.Notify);

then everything became OK.

The second problem in find has been resolved too. Just use like this:

Notify.findAll({
    include: ['User', 'Notification']
}).success(function (notify) {
    console.log(notify.user);
    console.log(notify.notification);
});


来源:https://stackoverflow.com/questions/13125050/confused-about-sequelize-associations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!