将模型的条件与其在Seq​​uelize

时间:2017-08-10 09:12:58

标签: javascript orm sequelize.js

有没有办法通过适用于其自己的字段到其关联域的条件来查找模型?

给定模型ModelAssociation,其中每个Model都有一个Association

const Model = sequelize.define('model', {
    name: sequelize.STRING,
});

const Association = sequelize.define('association', {
    name: sequelize.STRING,
});

Association.belongsTo(Model);
Model.hasOne(Association);

我想查找所有Model个,name等于"文字",Association name等于"文字"。

到目前为止,我提出了Sequelize.literal的解决方案,看起来不够健壮。

Model.findAll({
    attributes: ['id', 'name'],
    include: [{
        model: Association,
        attributes: [],
    }],
    where: {
        $or: [
            { name: 'test' },
            Sequelize.literal('association.name = \'test\''),
        ],
    },
});

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

文档中描述了此功能:this

Model.findAll({
    attributes: ['id', 'name'],
    include: [{
        model: Association,
        attributes: [],
    }],
    where: {
        $or: [
            { name: 'test' },
            { '$association.name$':  'test' },
        ],
    },
});