如何在特定情况下获取 Sequelize 中的关联元素
How to get associated elements in Sequelize for specific case
我有用户、项目和任务的模型
用户和任务具有多对多关联
项目和任务有一对多的关联(每个项目有很多任务)
当收到指定用户的任务时,我想为每个任务获取关联的项目。
任何人都可以帮助找到解决方法。
我的代码如下:
// receiving of user from database
const user = await User.findOne({where: {id: request.userId}})
// receiving of tasks related to user
const tasks = await user.getTasks(
// here i've tried to add following code, but it does not works
include: { model: Project, as: 'project' }
)
response.status(201).json( tasks )
如有帮助将不胜感激
在 Sequelize 中,在处理 'many' 关联时,可能会变得有些不同。你说你已经有这个协会:
Project.model
Project.hasMany(Task)
现在您需要在 Task.model 中实现另一种方式:
Task.belongsTo(Project);
在 Sequelize Documentation 你会发现:
To create a One-To-Many relationship, the hasMany and belongsTo
associations are used together;
我已经解决了问题。更正以下代码。
const user = await User.findByPk( request.userId )
if(!user) return
const tasks = await user.getTasks(
{ include: [
{ model: Project, as: 'project' }
] }
)
我有用户、项目和任务的模型
用户和任务具有多对多关联
项目和任务有一对多的关联(每个项目有很多任务)
当收到指定用户的任务时,我想为每个任务获取关联的项目。
任何人都可以帮助找到解决方法。
我的代码如下:
// receiving of user from database
const user = await User.findOne({where: {id: request.userId}})
// receiving of tasks related to user
const tasks = await user.getTasks(
// here i've tried to add following code, but it does not works
include: { model: Project, as: 'project' }
)
response.status(201).json( tasks )
如有帮助将不胜感激
在 Sequelize 中,在处理 'many' 关联时,可能会变得有些不同。你说你已经有这个协会:
Project.model
Project.hasMany(Task)
现在您需要在 Task.model 中实现另一种方式:
Task.belongsTo(Project);
在 Sequelize Documentation 你会发现:
To create a One-To-Many relationship, the hasMany and belongsTo associations are used together;
我已经解决了问题。更正以下代码。
const user = await User.findByPk( request.userId )
if(!user) return
const tasks = await user.getTasks(
{ include: [
{ model: Project, as: 'project' }
] }
)