left join on same table in sequelize

痞子三分冷 提交于 2019-12-11 17:23:51

问题


I want to write following query in sequelize but Not able to understand how to do.

SELECT * FROM RegisterUser AS RegisterUser LEFT OUTER JOIN Notification as Noti ON PM_UserID = Noti.ReceiveID LEFT OUTER JOIN RegisterUser AS RegisterUser1 ON Noti.SenderId = RegisterUser1.PM_UserID WHERE RegisterUser.PM_UserID = ReceiveID

I have written below query as a single left join and it works fine.

  RegisterUser.findAll({
include: [
  {
    model: Notification,
    as: 'NotificationrecipientId',
    required: false,
  },
],
raw: true });

And my assciotion is as follow:

db.RegisterUser.hasMany(db.Notifications, { as: 'NotificationrecipientId', foreignKey: 'ReceiveID' });

Sender ID as well in Register User table.


回答1:


For that you have define one more association :

db.Notification.belongsTo(db.RegisterUser, { as: 'Sender', foreignKey: 'SenderId' });

and then use it like :

RegisterUser.findAll({
    include: [{
        model: Notification,
        as: 'NotificationrecipientId',
        required: false,
        include: [{
            model: RegisterUser,
            as: 'Sender', // <---- HERE
            required: false,
        }, ]
    }, ],
    raw: true
});


来源:https://stackoverflow.com/questions/53591669/left-join-on-same-table-in-sequelize

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