Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

229
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!