问题
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