【问题标题】:Left excluding join in sequelize左不包括加入续集
【发布时间】:2017-08-24 15:03:21
【问题描述】:

我有两张表,其中一张有另一张的 ID。 1:1 的关系。 所以像

EventFeedback
    somePrimaryKey
    userEventID
UserEvent
    userEventID

Sequalize 具有用

定义的关系
models.UserEvent.hasOne(models.EventFeedback, { foreignKey: 'userEventID' });

我需要 UserEvent 中没有 EventFeedback 中的条目的所有条目,这是一个排除性连接。 从this article 窃取图像,因为它们具有漂亮的单个图像:

他们甚至给出了示例代码!

SELECT <select_list> 
FROM Table_A A
LEFT JOIN Table_B B
ON A.Key = B.Key
WHERE B.Key IS NULL

我如何在 sequelize 中做到这一点? 我只需要进行左连接并手动处理吗?

【问题讨论】:

    标签: sequelize.js


    【解决方案1】:

    您需要在查询UserEvent 时预先加载EventFeedback 并添加适当的where 子句。您还需要定义结果中不需要EventFeedback,因此查询将生成LEFT JOIN 而不是INNER JOIN

    UserEvent.all({
        include: [
            model: EventFeedback,
            required: false, // do not generate INNER JOIN
            attributes: [] // do not return any columns of the EventFeedback table
        ],
        where: sequelize.where(
            sequelize.col('EventFeedback.userEventID'),
            'IS',
            null
        )
    }).then(userEvents => {
        // user events...
    });
    

    在上面的代码中,sequelize 是 Sequelize 的一个实例,其中定义了模型。也可以参考sequelize.where()sequelize.col()方法的文档。

    【讨论】:

      【解决方案2】:

      默认情况下,SEQUALIZE 始终使用 INNER JOIN。 让它左连接很容易。 只需添加...

      required: false 
      

      连同代码。 按照示例查询代码。

       UserModel.findAll({
              attributes: {
                  exclude: ['role_id', 'username', 'password', 'otp', 'active']
              },
              where: {
                  active: 1,
                  role_id: 2
              },
              include: [{
                  model: StateModel,
                  attributes: ['id', 'short_name'],
                  as: 'state_details',
                  where: {
                      active: 1
                  },
                  required: false
              }]
          }).then(List => {
              console.log(List);
          }).catch(err => {
              console.log(err);            
       });
      

      【讨论】:

      • 添加 required:false 是不够的。
      猜你喜欢
      • 1970-01-01
      • 2015-03-26
      • 2013-05-27
      • 2015-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-15
      • 2013-01-22
      相关资源
      最近更新 更多