在 sequelize 中左连接同一张表 [英] left join on same table in sequelize

查看:54
本文介绍了在 sequelize 中左连接同一张表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 sequelize 中编写以下查询,但无法理解该怎么做.

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

SELECT * FROM RegisterUser AS RegisterUserLEFT OUTER JOIN 通知为 Noti ON PM_UserID = Noti.ReceiveIDLEFT OUTER JOIN RegisterUser AS RegisterUser1 ONNoti.SenderId = RegisterUser1.PM_UserIDWHERE 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 });

我的关联如下:

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

注册用户表中的发件人 ID.

Sender ID as well in Register User table.

推荐答案

为此你又定义了一个关联:

For that you have define one more association :

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
});

这篇关于在 sequelize 中左连接同一张表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆