Basant Singh
Basant Singh

Reputation: 5926

Sequelize joining tables with multiple records with same foreign key

I have sequelize database with 3 models.

  1. Team - primary key: id
  2. Participant - foreignKey refering to Team - teamId
  3. TeamResult- foreignKey refering to Team - teamId

Each team can have multiple participants so there can be multiple records in participant table having same teamId. Same case with team results.

I am trying to right a query where I get an object with all the participants and team results associated with the team in the following manner:

{
    "id": 1,
    "teamName": "Awesome Team",
    //other team attributes..


    "participants": [
        {
            "id": 12,
            "teamId": 1,
            //other details
        },
        {
            "id": 13,
            "teamId": 1,
            //other details
        },
    ],

    "teamResults": [
        {
            "id": 22,
            "teamId": 1,
            //other details
        },
        {
            "id": 13,
            "teamId": 1,
            //other details
        }
    ]
}

I have wrote the following statement but all I get is just first one of Participants and Mentors, not all of them:

models.Team.find({
        where: {
            id: req.params.teamId
        },
        include: [
            {model: models.Participant, required: true},
            {model: models.TeamResult, required: true}
        ]
    }).then(function(team){/* handle team object here */})

What changes do I need to make in order to get the required result?

Upvotes: 2

Views: 2405

Answers (1)

Basant Singh
Basant Singh

Reputation: 5926

Solved it myself. Made a silly mistake. Instead of hasMany association, I was using hasOne in the team's associations. Fixed now.

Upvotes: 3

Related Questions