Habib Ur Rehman
Habib Ur Rehman

Reputation: 131

How to get multiple association results in sequelize

i have problem fetching the association results.

I have two models 1 - User 2 - Project

User.hasMany(Project, { foreignKey : 'user_Id' }); Project.belongsTo(User, { foreignKey: { name: 'user_Id', type: DataTypes.UUID } })

when i fetch data through Project Model then corresponding user info is also fetched.

    getAllProjects: async (req, res) => {
        const projects = await Project.findAll({ include: User});
        res.json({projects})
    }

Result of above code

results

{
    "projects": [
        {
            "id": "9bb3b99c-ac14-48fa-a0f2-e707f1d517ad",
            "name": "this is project name",
            "budget": "$34",
            "details": null,
            "days": null,
            "deadline": null,
            "user_Id": "02ef60af-0b1e-45e9-b393-55e124673143",
            "start_date": null,
            "status": 0,
            "createdAt": "2022-03-23T03:02:56.000Z",
            "updatedAt": "2022-03-23T03:02:56.000Z",
            "User": {
                "id": "02ef60af-0b1e-45e9-b393-55e124673143",
                "name": null,
                "email": null,
                "password": null,
                "userType": "client",
                "createdAt": "2022-03-23T03:02:35.000Z",
                "updatedAt": "2022-03-23T03:02:35.000Z"
            }
        }
    ]
}

But in reverse when i try to fetch user with their projects, user info is fetched but the associated projects are not fetched.

Code

getAllUsers: async (req, res) => {
    const users = await User.findAll({inlcude: [{model: Project}]})
    res.json({users})
}

** Result of above code**

{
    "users": [
        {
            "id": "02ef60af-0b1e-45e9-b393-55e124673143",
            "name": null,
            "email": null,
            "password": null,
            "userType": "client",
            "createdAt": "2022-03-23T03:02:35.000Z",
            "updatedAt": "2022-03-23T03:02:35.000Z"
        }
    ]
}

Please help me. Thanks in advance.

Upvotes: 0

Views: 91

Answers (1)

Anatoly
Anatoly

Reputation: 22783

Simply correct typo from inlcude to include.

const users = await User.findAll({include: [{model: Project}]})

Upvotes: 1

Related Questions