【问题标题】:Sequelize - Where clause using the included model attributeSequelize - 使用包含的模型属性的 Where 子句
【发布时间】:2020-07-21 19:28:17
【问题描述】:

使用sequelize,我需要找到所有满足以下条件的文章:article.isSecret = false OR article.board.managerId = user.userId OR article.authorId = user.userId。以下是我写的代码:

const articles = await Articles.findAll({
    include: [{
        model: Boards, 
        as: 'board', 
        attributes: ['managerId'], 
        required: true, 
    }], 
    where: {
        [Op.or]: [{
            isSecret: false, 
        }, {
            'board.managerId': user.userId, 
        }, {
            authorId: user.userId, 
        }], 
    }, 
    attributes: ['id', 'title', 'authorId', 'createdAt'], 
});

但是代码抛出了一个错误Unknown column 'article.board.managerId' in 'on clause'。在 where 子句中加载父模型值的正确方法是什么?我试过$board.managerId$$Boards.managerId$,但是都没有加载article.board.managerId的值。

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    我终于能够解决这个问题,我会在这里写下我的解决方案来帮助任何面临同样问题的人。将 where 子句放入包含的模型中,在本例中为 Boards 模型。

    const articles = await Articles.findAll({
        include: [{
            model: Boards, 
            as: 'board', 
            where: {
                [Op.or]: [{
                    '$article.isSecret$': false, 
                }, {
                    managerId: user.userId, 
                }, {
                    '$article.authorId$': user.userId, 
                }], 
            }, 
            attributes: ['managerId'], 
            required: true, 
        }], 
        attributes: ['id', 'title', 'authorId', 'createdAt'], 
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-27
      • 2019-02-17
      • 1970-01-01
      • 1970-01-01
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多