Sequelize - How to get a list of nested table entries (Project -> Task through Milestones)?

夙愿已清 提交于 2019-12-23 03:38:29

问题


Lets say I have the tables User, Project, Milestone, Task

User.belongsToMany(Project, {through: ProjectUser})
Project.belongsToMany(User, {through: ProjectUser})

Project.hasMany(Milestone)
Milestone.belongsTo(Project)

Milestone.hasMany(Task)
Task.belongsTo(Milestone)

Now I can easily get all Milestones in a Project where a User belongs to:

User.findAll({
    include: [{ 
        model: Project,
        include: [{
            model: Milestone
            include: [ Task ]
        }]
    }]

Now I would like to get the Tasks not inside the Milestones. Instead I would like to get the Tasks parallel to Milestones. Like this:

User.findAll({
    include: [{ 
        model: Project,
        include: [
            Milestone,
            Task
        ]
    }]

But if I do it like this I get as expected:

Unhandled rejection Error: Task is not associated to Project! 

I could use a Project.hasMany(Task) but then I would need to add a ProjectId column to the Task table. I would like to avoid that. So I thought about

Project.belongsToMany(Task, { through: Milestone })

But this gives me the following error:

Unhandled rejection SequelizeDatabaseError: column Projects.Tasks.Milestones.TaskId does not exist

I know that and Milestones can't contain a TaskId as Milestones have multiple Tasks. So the reference between Milestone and Task is stored in Task as MilestoneId.

Anyone a Idea how I get a List with all Tasks which belong to the Project without adding a ProjectId to Tasks??

来源:https://stackoverflow.com/questions/34483863/sequelize-how-to-get-a-list-of-nested-table-entries-project-task-through-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!