node.js - 使用其中包含的内容对查询进行序列化

标签 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;
};

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

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

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

最佳答案

你得到这个结果是因为查询中的 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'
    }]
})

关于node.js - 使用其中包含的内容对查询进行序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38821389/

相关文章:

javascript - 在构建时执行NormalModule,由加载器构建后,然后保存到json文件

javascript - 确定 Meteor/Node 中服务器返回的输出是客户端上的 stderr 还是 stdout?

node.js - 如何在 Mongoose 中填充嵌套实体?

node.js - 如何将填充的 Mongoose 对象传递给渲染代码?

node.js - 如何从中间件获取api结果到路由

node.js - Sequelize 需要

javascript - 如何在Sequelize中按多对多关系排序?

javascript - 自异步以来如何优化此代码块

javascript - Node、Express + Jade 加载脚本一次

node.js - 使用快速 Passport 和 Sequelize 进行电子邮件验证