0

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.