gpt4 book ai didi

javascript - Node JS Sequelize 连接查询

转载 作者:行者123 更新时间:2023-12-03 22:22:38 37 4
gpt4 key购买 nike

我是 Sequelize 的新手,就像我今天必须学习一样。我什至不知道如何提出问题,所以请让我知道我该如何改进。我有以下查询。

router.get('/:id/work', async (req, res) => {
let results = await User.findAll(
{
where: {
id: req.params.id
},
include: [Task, Project]
}
);
res.status(200);
res.send(results);
});


我想获取用户信息,并将“tasks”和“projects”作为“assigner”和“project_id”属性的数组。我的 Project 和 Task 模型都将这些列作为外键。
我得到的结果是下面的

{
id: 5,
email: "asd@asdads.com",
name: "asdasdasd",
surname: "asdasdasdasd1231",
Task: {
id: 9,
name: "req.body.name",
description: "req.body.description",
score: 1,
status: "req.body.status",
assigner: 5,
project_id: null
},
Project: {
id: 2,
name: "req.body.name",
body: "req.body.body",
status: null,
assigner: 5
}
},
{
id: 5,
email: "asd@asdads.com",
name: "asdasdasd",
surname: "asdasdasdasd1231",
Task: {
id: 9,
name: "req.body.name",
description: "req.body.description",
score: 1,
status: "req.body.status",
assigner: 5,
project_id: null
},
Project: {
id: 3,
name: "req.body.name",
body: "req.body.body",
status: "req.body.status",
assigner: 5
}
},

有什么快速的方法可以实现这一目标吗?
{
id: 5,
email: "asd@asdads.com",
name: "asdasdasd",
surname: "asdasdasdasd1231",
Task: [/*all task objects*/],
Project: [/*all project objects*/]
}

模型定义
const User = db.define('User', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
},
email: Sequelize.STRING,
name: Sequelize.STRING,
surname: Sequelize.STRING,
}, {
timestamps: false,
tableName: 'users'
})

/**
* Model Relations
*/

Project.belongsTo(User, { foreignKey: 'assigner' })
User.hasOne(Project, { foreignKey: 'assigner' })

Task.belongsTo(User, { foreignKey: 'assigner' })
User.hasOne(Task, { foreignKey: 'assigner' })

Task.belongsTo(Project, { foreignKey: 'project_id' })

export default User;

const Task = db.define('Task', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: Sequelize.STRING,
description: Sequelize.TEXT,
score: Sequelize.INTEGER,
status: Sequelize.STRING,
assigner: {
type: Sequelize.INTEGER,
references: {
model: User,
key: 'id'
}
},
project_id: {
type: Sequelize.INTEGER,
references: {
model: Project,
key: 'id'
}
}
}, {
timestamps: false,
tableName: 'tasks'
})


export default Task;
const Project = db.define('Project', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: Sequelize.STRING,
body: Sequelize.STRING,
status: Sequelize.STRING,
assigner: {
type: Sequelize.INTEGER,
references: {
model: User,
key: 'id'
}
}
}, {
timestamps: false,
tableName: 'projects'
})

export default Project;

最佳答案

将关联定义从 hasOne 更改为 hasMany,因为正如我所见,许多项目可以链接到一个用户以及任务:

User.hasMany(Project, { foreignKey: 'assigner' })
User.hasMany(Task, { foreignKey: 'assigner' })

关于javascript - Node JS Sequelize 连接查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62178517/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com