Reputation: 202
I have a problem in the listing of records with belongsToMany association using sequelize + nodejs.
I have the developers and technologies tables. The relationship between them is many to many. To create a relationship, use a pivot table called developers_technologies.
Below is a gist with the code of: Models (developers, technologies), migration (developers_technologies) and controller of Developers.
https://gist.github.com/fredarend/85ff60fca70643d80301b499e871c4a6
The code of the Index of the controller Developer 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);}
Return:
[
{
"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 the developer, since the developers_technologies table in the database is populated and the relationships in the models are ok.
EDIT: query generated from the request:
SELECT
"Developer"."id",
"Developer"."name",
"Developer"."email",
"technologies"."id" AS "technologies.id",
"technologies"."name" AS "technologies.name",
"technologies->developers_technologies"."created_at" AS "technologies.developers_technologies.createdAt",
"technologies->developers_technologies"."updated_at" AS "technologies.developers_technologies.updatedAt",
"technologies->developers_technologies"."developer_id" AS "technologies.developers_technologies.developer_id",
"technologies->developers_technologies"."technology_id" AS "technologies.developers_technologies.technology_id"
FROM "developers" AS "Developer"
LEFT OUTER JOIN ( "developers_technologies" AS "technologies->developers_technologies"
INNER JOIN "technologies" AS "technologies" ON "technologies"."id" = "technologies->developers_technologies"."developer_id") ON "Developer"."id" = "technologies->developers_technologies"."technology_id";
Kind regards,
Upvotes: 0
Views: 1140
Reputation: 22758
Try to indicate otherKey
in belongToMany
associations. Also you indicated wrong foreign keys. For Developer it should be developer_id
and for Technology it should be technology_id
:
Model - Developer
this.belongsToMany(models.Technology, {
foreignKey: 'developer_id',
otherKey: 'technology_id',
through: 'developers_technologies',
as: 'technologies',
});
Model - Technology
this.belongsToMany(models.Developer, {
foreignKey: 'technology_id',
otherKey: 'developer_id',
through: 'developers_technologies',
as: 'developers',
});
Upvotes: 2