Belongstomany Relationship - Sequelize

Asked

Viewed 102 times

-2

Hello, I have a problem in listing records with belongsToMany association using sequelize + nodejs.

I have the tables Developers and Technologies. The relationship between them is Many to Many. To create the relationship, I used a pivot table called developers_technologies.

Below is a gist with the code of: Models (Developers, Techonologies), Migration (developers_technologies) and controller of Developers.

https://gist.github.com/fredarend/85ff60fca70643d80301b499e871c4a6

The Index code of the Developer controller is this:

async index(req, res) {
const developers = await Developer.findAll({
  attributes: ['id', 'name', 'email'],
  include: [
    {
      model: Technologies,
      as: 'technologies',
      attributes: ['id', 'name'],
      through: { attributes: [] },
    },
  ],
});

return res.json(developers);}

The return I’m getting is:

[
    {
        "id": 25,
        "name": "Jon Doe",
        "email": "[email protected]",
        "age": 27,
        "url_linkedin": "http://asdasdasd",
        "technologies": []
    }
]

I would like to know why I am not receiving Technologies linked to Veloper, and there is the table developers_technologies in the database is populated and the relations in models are ok.

Sincerely yours,

1 answer

-2

look missed the association (Association)

do so :

async index(req, res) {
  const developers = await Developer.findAll({
    attributes: ['id', 'name', 'email'],
    include: [
      {
        model: Technologies,
        as: 'technologies',
        association: 'nome da associacao', attributes: ['id', 'name'],
        through: { attributes: [] },
      },
    ],
  });

  return res.json(developers);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.