Shaju Nr
Shaju Nr

Reputation: 358

sequelize indirect associations

I have 3 tables named projects,workspace,views and the associations are

projects.hasMany(workspace); 
workspace.belongsTo(projects); 

workspace.hasMany(views);
views.belongsTo(workspace);

I need to join these 3 tables to get the output of following query

select * from projects pro join workspace wrk on  pro.id= wrk.project_id 
join views on wrk.id = views.workspace_id

I tried an association

views.belongsTo(projects, { through: workspace.associations.projects });

Following is the code:

View.findAll({
   include: [
     {model: db.workspaces, required: true},
     {model: db.projects, required: true}
   ]
});

But it generates the query

SELECT *
FROM "views" AS "views"
INNER JOIN "workspaces" AS "workspace" ON "views"."workspace_id" = "workspace"."id"
INNER JOIN "projects" AS "project" ON "views"."project_id" = "project"."id"

The project_id does not exists in views table.It associates the views only through workspace.How can it be achieved.

Upvotes: 2

Views: 487

Answers (1)

Vikash Dahiya
Vikash Dahiya

Reputation: 5801

Try following

Project.hasMany(Workspace,{foreignKey : 'project_id'}); 
Workspace.belongsTo(Project);

Workspace.hasMany(views,{foreignKey: 'workspace_id'});
View.belongsTo(Workspace);

Workspace.findAll({
   include: [
     {model: View, required: true},
     {model: Project, required: true}
   ]
});

Upvotes: 2

Related Questions