简体   繁体   English

Sequelize:Include.where 按“父”模型属性过滤

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

I have two Models related, Catalog and ProductCategory.我有两个相关的模型,目录和产品类别。 The latter has a composed PK, 'id, language_id'.后者有一个组合 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.我试图从与目录相关的 ProductCategory 表中包含一些信息,但仅当 language_id 匹配时。

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 clause, without any consecuence:顺便说一句,我也尝试过更改 where 子句,没有任何后果:

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

Sequelize provides an extra operator $col for this case so you don't have to use sequelize.literal('...') (which is more a hack). Sequelize 为这种情况提供了一个额外的运算符$col ,因此您不必使用sequelize.literal('...') (这更像是一个黑客)。

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

You can try this (Especially if you are using MariaDB) -你可以试试这个(特别是如果你使用的是 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'}
        }
    }
})

这似乎可以解决问题:

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

Or even just try this:或者甚至只是试试这个:

const models = require("models directory");
    {
       model: models.ModelName,
       where: {
            column-name: column-value
         }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM