Home > Net >  How to get nested "Sequelize" data?
How to get nested "Sequelize" data?

Time:02-15

I have created a Sequelize ORM based PostgreSQL database. I have implemented some relation between product and reviews. And, each review has been posted by a user. So, when I am querying for a single product, I want the data with, product, reviews & inside review I want to see who posted as well means user.

{
    "id": 1,
    "name": "Rounded Neck T-Shirt",
    "title": "some title",
    "snippet": "some snippet od demin t shirt",
    "details": "some details",
    "moreInfo": "some moreInfo",
    "size": "size will be in a seperate table this will be FK",
    "stock": 452,
    "askingPrice": 4299,
    "offPrice": null,
    "offer": null,
    "ratings": null,
    "images": null,
    "pictureUrl": "https://loopinfosol.in/themeforest/ekka-html-v31/ekka-html/assets/images/product-image/6_2.jpg",
    "purchaseCost": 4200,
    "createdAt": "2022-02-14T10:59:55.999Z",
    "updatedAt": "2022-02-14T11:07:12.916Z",
    "categoryId": 1,
    "userId": 1,
    "reviews": [
        {
            "id": 1,
            "rating": 5,
            "comment": "Very nice product",
            "createdAt": "2022-02-14T17:28:22.680Z",
            "updatedAt": "2022-02-14T17:28:22.680Z",
            "productId": 1,
            "userId": 1
        }
    ]
}

Here, "userId" is the foreign key for the registered user id. I want to see the user data inside "reviews" as well. How can I do that?

I get the above JSON data by querying the following code.

  Product.findOne({
    include: [Review],
    where: { id: req.params.id },
  })

CodePudding user response:

If you already have an association definition like Review.belongsTo(User, ... then you simply need to indicate a nested include option with User model:

Product.findOne({
    include: [{
     model: Review,
     include: [{
       model: User
     }]
    }],
    where: { id: req.params.id },
  })
  • Related