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?
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.