Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double include in sequelize, node.js

I want to include another Model to my User.findAll function. The SurveyResult model belongs the Model Survey. How can i include the Model Survey to show the Survey whitch belongs to the SurveyResult

async index (req, res) {
    try {
        const userData = await User.findAll({
            include: [ UserStatus, SurveyResult
            ]
        })
            .map(user => user.toJSON())
        
        res.send(userData)
    } catch (err) {
        console.log(err)
    }
    
}

Here is my json i get back:

 {
    "id": 3,
    "email": "[email protected]",
    "password": "$2a$08$Y22dOOIgyGhLAOokYluGxupKHRv8zRcbAVK1YEvWVUtoBl7dOsAYK",
    "name": "test",
    "forename": "test",
    "createdAt": "2018-12-05T11:25:30.000Z",
    "updatedAt": "2018-12-05T11:25:30.000Z",
    "AdminId": 1,
    "UserStatuses": [
        {
            "id": 3,
            "sendEmail": false,
            "sendResult": true,
            "createdAt": "2018-12-05T11:25:31.000Z",
            "updatedAt": "2018-12-05T11:25:31.000Z",
            "UserId": 3
        }

i tried that but it dont work:

 const userData = await User.findAll({
    include: [
      { UserStatus, SurveyResult, include: [Survey] }
    ]
  })
    .map(user => user.toJSON())
like image 695
Josef Henn Avatar asked Dec 28 '25 19:12

Josef Henn


1 Answers

I think you are trying to include on nested levels , if that's the case you can do it this way

const userData = await User.findAll({
    include: [
        { model : UserStatus }
        { model : SurveyResult ,
            include: {
                model : Survey
            } 
        }
    ]
})

// OR ( Shorthand )

const userData = await User.findAll({
    include: [ UserStatus , { model : SurveyResult , include: [Survey] }]
})
like image 76
Vivek Doshi Avatar answered Dec 31 '25 11:12

Vivek Doshi