使用 where 内包含的 Sequelize 查询

C. *_*lik 7 node.js express sequelize.js

我有以下型号:

'use strict';

module.exports = function(sequelize, DataTypes) {
    var Collection = sequelize.define("Collection", {
        name: DataTypes.STRING,
        customer: DataTypes.STRING
    }, {
        classMethods: {
            associate: function(models) {
                Collection.hasMany(models.Items);
            }
        }
    });

    return Collection;
};


'use strict';

module.exports = function(sequelize, DataTypes) {
    var Item = sequelize.define("Item", {
        itemId: {
            type: DataTypes.STRING,
            primaryKey: true
        }
    }, {
        classMethods: {
            associate: function(models) {
                Item.belongsToMany(models.Collection);
            }
        }
    });

    return Item;
};
Run Code Online (Sandbox Code Playgroud)

假设我想获取特定客户的所有集合及其项目,其中一个项目包含 itemId。我的查询如下:

models.Collection.findAll({
    where: {
      customer: customerParam
    },
    include: [{
        model: models.Item,
        where: {
          itemId: itemParam
        }
    }]
}).then(function(collections) {
    console.log(collections);
}) 
Run Code Online (Sandbox Code Playgroud)

问题是这个查询从我得到的集合中过滤项目,现在它们只包含具有相同 itemId 的项目,而不是包含集合的所有项目。

Til*_*bek 11

由于查询中的 where 语句像子查询一样单独执行,因此您会得到此结果。因此,如果您想生成类似的 where 子句,WHERE Collection.customer = 'blabla' AND Item.itemId = 1您应该执行以下操作:

models.Collection.findAll({
    where: {
      customer: customerParam,
      '$items.itemId$': itemParam
    },
    include: [{
        model: models.Item,
        as: 'items'
    }]
})
Run Code Online (Sandbox Code Playgroud)