Sequelize: Include.where filtering by a 'parent' Model attribute

大憨熊 提交于 2020-06-09 11:55:16

问题


I have two Models related, Catalog and ProductCategory. The latter has a composed PK, 'id, language_id'. Here are the models simplified:

var Catalog = sequelize.define("Catalog", {
id: {
  type: DataTypes.INTEGER,
  primaryKey: true,
  autoIncrement: true
},
user_id: {
  type: DataTypes.INTEGER,
  allowNull: false
},
product_category_id: {
  type: DataTypes.STRING(7)
},
language_id: {
  type: DataTypes.INTEGER
},  
... more stuff ...
}

var ProductCategory = sequelize.define("ProductCategory", {
id: {
  type: DataTypes.STRING(7),
  primaryKey: true
},
language_id: {
  type: DataTypes.INTEGER,
  primaryKey: true
},
... more stuff ...
}

Catalog.belongsTo(models.ProductCategory, {foreignKey: 'product_category_id'});

I'm trying to include some info from ProductCategory table related to Catalog, but ONLY when the language_id matches.

At the moment I'm getting all the possible matches from both tables. This is the query right now:

Catalog.find({where:
    {id: itemId},
    include: {
        model: models.ProductCategory, 
        where: {language_id: /* Catalog.language_id */}
    }
})

Is there a way to use an attribute from Catalog to filter the include where both models have the same language?

By the way, I've also tried changing the where caluse, without any consecuence:

where: {'ProductCategory.language_id': 'Catalog.language_id'}

回答1:


Sequelize provides an extra operator $col for this case so you don't have to use sequelize.literal('...') (which is more a hack).

In your example the usage would look like this:

Catalog.find({where:
    {id: itemId},
    include: {
        model: models.ProductCategory, 
        where: {
          language_id: {$col: 'Catalog.language_id'}
        }
    }
})



回答2:


You can try this (Especially if you are using MariaDB) -

const Sequelize = require('sequelize'); 
const op = Sequelize.Op;

Catalog.find({where:
    {id: itemId},
    include: {
        model: models.ProductCategory, 
        where: {
          language_id: {[op.col]: 'Catalog.language_id'}
        }
    }
})



回答3:


This seems this do the trick:

where: {language_id: models.sequelize.literal('Catalog.language_id')}


来源:https://stackoverflow.com/questions/30052254/sequelize-include-where-filtering-by-a-parent-model-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!