sequelize在同一张桌子上左联接

时间:2018-12-03 10:21:09

标签: node.js sequelize.js

我想按顺序编写以下查询,但不知道该怎么做。

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

我在下面的查询中将其写为单个左联接,并且工作正常。

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

我的奉献如下:

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

“注册用户”表中的发件人ID。

1 个答案:

答案 0 :(得分:1)

为此,您还定义了一个关联:

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

然后像这样使用它:

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