'Is there any way in Sequelize to search on a table with data in another table which is a foreign key to that table?
My product table
const Product = sequelize.define('products', {
id: {
type: Sequelize.STRING(12),
allowNull: false,
primaryKey: true,
},
name: {
type: Sequelize.STRING(100),
allowNull: false,
unique: true,
},
brand: {
type: Sequelize.STRING(40),
allowNull: false,
},
instock: {
type: Sequelize.INTEGER,
defaultValue: 0,
allowNull: false,
},
mrp: {
type: Sequelize.DECIMAL,
defaultValue: 0.0,
allowNull: false,
},
price: {
type: Sequelize.DECIMAL,
defaultValue: 0.0,
},
createdAt: Sequelize.DATE,
updatedAt: Sequelize.DATE,
});
Product.belongsTo(Category, {
foreignKey: 'category_id',
as: 'categorys',
});
Here the category is a foreign key. I want to search with category name. Do I need to fetch the category first and use the id to search for products?
Solution 1:[1]
You definitely can search by fields in an associated model, just use where option inside include:
const products = await Products.findAll({
include: [{
model: Category,
as: 'categorys',
required: true,
where: {
name: categoryName
}
}]
})
If you already have a category id then better search products by it, that way you won't need to use include option at all.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anatoly |
