gourav kumar
gourav kumar

Reputation: 150

sequelize get column value of referenced table

I have three tables meetings, rooms and projects

meetings.belongsTo(models.rooms, { foreignKey: "room_id" , targetKey: "id"});
rooms.hasMany(models.meetings, { foreignKey : "id", targetKey : "room_id"});
rooms.belongsTo(models.projects, { foreignKey: "project_id", targetKey: "id"});
projects.hasMany(models.rooms,  {foreignKey:"id", targetKey:"project_id"});

id, room_id and project_id are primary key of their respective table. I want to find value of some column of projects for a particular meeting id. How to write a single query using sequelize nodejs to do this? below query need to execute using sequelize which is giving correct result

select project_meta from projects  p
inner join rooms  r on p.id = r.project_id
inner join  meetings  m on  r.id = m.room_id
where  m.id = "QBZJ0TK7V6NFSPPWGFNCN";

wrote following

projects.findAll({
    include: [{
        model: rooms,
        include: [{
            model: meetings,
            where: {
                id: "QBZJ0TK7V6NFSPPWGFNCN"
            }
        }]
    }],
    attributes: ['project_meta']
}

but it is executing different query and giving unexpected result

is there any problem with association?

Upvotes: 0

Views: 1741

Answers (1)

Naor Levi
Naor Levi

Reputation: 1813

You must use SQL joins (sequelize's include)

function myQuery(meetingId) {
    let options = {};
    options.attributes = ['column1', 'column2', ...]; // The specific arrtibutes you need.
    options.include = [
        {
            model: RoomModel,
            include: [
                {
                    model: MeetingModel,
                    where: {
                        id: meetingId  // The specific meeting id
                    }
                }
            ]
        }
    ];
    ProjectModel.findAll(options);
}

Upvotes: 1

Related Questions