【发布时间】:2020-12-16 18:05:53
【问题描述】:
我在使用 sequelize + nodejs 列出具有 belongsToMany 关联的记录时遇到问题。
我有开发人员和技术表。他们之间的关系是多对多的。要创建关系,请使用名为 developers_technologies 的数据透视表。
以下是代码的要点:模型(开发人员,技术),迁移(developers_technologies)和开发人员的控制器。
https://gist.github.com/fredarend/85ff60fca70643d80301b499e871c4a6
控制器开发者的Index代码是这样的:
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);}
返回:
[
{
"id": 25,
"name": "Jon Doe",
"email": "jondoe@gmail.com",
"age": 27,
"url_linkedin": "http://asdasdasd",
"technologies": []
}
]
我想知道为什么我没有收到与开发人员相关的技术,因为数据库中的 developers_technologies 表已填充并且模型中的关系正常。
编辑: 从请求生成的查询:
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";
亲切的问候,
【问题讨论】:
标签: node.js api rest express sequelize.js