使用 Sequelize for Node JS 将 where 子句添加到连接 table 时遇到问题

Having trouble adding a where clause to a join table using Sequelizer for NodeJS

我正在执行以下where。导致我出现问题的关键逻辑在第 7 行,我试图在其中指定连接 table 的 where 条件。

models.Portfolio.findAll({
        include: [{
            model: models.PortfolioPermissions,
        }],
        where: models.sequelize.or(
            {'userId': userId},
            {'PortfolioPermissions.userId': userId}
        ),
        order: [['startDate', 'DESC']]
    })

您可以看到下面生成的查询在第 9 行中有一个主要问题。 Sequelize 在我的 where 子句前面加上投资组合 table,这把一切都搞砸了。

SELECT `portfolios`.*,
       `sharedUsers`.`id` AS `sharedUsers.id`,
       `sharedUsers`.`permissions` AS `sharedUsers.permissions`,
       `sharedUsers`.`userId` AS `sharedUsers.userId`,
       `sharedUsers`.`portfolioId` AS `sharedUsers.portfolioId`
FROM `portfolios`
LEFT OUTER JOIN `portfolioPermissions` AS `sharedUsers` ON `portfolios`.`id` = `sharedUsers`.`portfolioId`
WHERE (`portfolios`.`userId`=1
       OR `portfolios`.`PortfolioPermissions.userId`=1)
ORDER BY `startDate` DESC;

如果有人能在这里指出正确的方向,我将不胜感激。太感谢了。我正在使用 Postgres FYI,不过可能不相关。

连接 table 的条件应放在相关的 include 条目中,而不是放在全局 where 条件中。 在您的情况下,类似以下的内容应该有效:

models.Portfolio.findAll({
    include: [{
        model: models.PortfolioPermissions,
        where: {'userId': userId}

    }],
    where: models.sequelize.or(
        {'userId': userId}
    ),
    order: [['startDate', 'DESC']]
})