簡體   English   中英

使用 where 內包含的 Sequelize 查詢

[英]Sequelize query with where inside include

我有以下型號:

'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 子句WHERE Collection.customer = 'blabla' AND Item.itemId = 1您應該執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM