序列化-使用或运算符与模型关联进行查询

时间:2019-02-19 20:15:27

标签: node.js sequelize.js

使用 Sequelize ,我有两个具有多对多关联的模型:UserCategory
我想获取属于当前用户的所有类别,以及具有特定属性的类别,但是我不知道怎么做,仅需一个查询...

根据documentation和关联模型的Op.or语法,我正在使用$Model.attribute$运算符(见here)。

let categories = await models.category.findAll({
        where: {
            [Op.or]: [
                { someCategoryProperty: true },
                { '$User.id$': req.currentUser.id },
            ],
        },
        include: [{
            model: models.user,
            as: 'User',
        }],
    });

如果我为Category模型添加2个条件,该运算符将起作用,但是如何在关联上添加一个条件?

1 个答案:

答案 0 :(得分:0)

我终于找到了提示:

实际上,$Model.attribute$不是好的模式,$database_table_name.attribute$是好的模式。

使用'$..$'语法,我们必须使用数据库表名称,而不是模型。
如果我的模型名为user,则Sequelize设置数据库名称 users

因此此代码有效:

let categories = await models.category.findAll({
        where: {
            [Op.or]: [
                { someCategoryProperty: true },
                { '$users.id$': req.currentUser.id },
            ],
        },
        include: [{
            model: models.user,
        }],
    });

谢谢