Monday, May 20, 2024
136
rated 0 times [  138] [ 2]  / answers: 1 / hits: 71042  / 9 Years ago, tue, may 5, 2015, 12:00:00

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 clause, without any consecuence:


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

More From » sequelize.js

 Answers
30

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

[#66737] Monday, May 4, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaredsages

Total Points: 273
Total Questions: 97
Total Answers: 105

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
jaredsages questions
;