user3722208
user3722208

Reputation: 1

How to include more than one other table using Sequelize?

I have the following tables:

Product:
name: string, description: string, image: string

Brand:
name: string

Category:
name: string

One Product can only have One Brand. One Product can have multiple Categories.

My associations are:

models/product.js:
Product.associate = function(models) {
    Product.hasOne(models.Brand, {
      foreignKey: "productId",
      as: "brand"
    }),
      Product.hasMany(models.Category, {
        foreignKey: "productId",
        as: "categories"
      });
  }
models/category.js:
Category.belongsTo(models.Product, {
      foreignKey: "productId",
      onDelete: "CASCADE"
    })
models/brand.js:
Brand.belongsTo(models.Product, {
      foreignKey: "productId",
      onDelete: "CASCADE"
    })

1- is it OK so far? The indentation in models/product.js seems odd to me.

2- in my Products controller, how do I retrieve both the brand and the categories of my products? Currently I have:

controllers/products.js:
list(req, res) {
    return Product.findAll({
      include: [
        {
          model: Category,
          as: "categories"
        }
      ]
    })
      .then(products => res.status(200).send(products))
      .catch(error => res.status(400).send(error));
  }

Categories are included, how do I also include the brand?

I expect the output to be an array of products that all contain a brand and one or more categories.

Upvotes: 0

Views: 369

Answers (1)

BDrought
BDrought

Reputation: 195

Given the established associations, you should be able to add the other model, comma-delimited, like so:

controllers/products.js:
list(req, res) {
    return Product.findAll({
      include: [
        {
          model: Category,
          as: "categories"
        },
        {
          model: Brand,
          as: "brand"
        }
      ]
    })
      .then(products => res.status(200).send(products))
      .catch(error => res.status(400).send(error));
  }

Upvotes: 2

Related Questions