【问题标题】:Sequelize query with where inside include使用 where 内部包含的 Sequelize 查询
【发布时间】:2016-12-13 18:24:52
【问题描述】:

我有以下型号:

'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;
};

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

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

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

【问题讨论】:

    标签: node.js express sequelize.js


    【解决方案1】:

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

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

    【讨论】:

    • 当我激活查询时,它现在抛出以下异常:未处理的拒绝错误:项目(项目)未关联到集合!
    • 仅添加类似“$items.itemId$”的查询就帮了我很多忙:itemParam 有效。伟大的。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 2021-02-09
    • 2020-06-17
    相关资源
    最近更新 更多