如何获取嵌套的"Sequelize"数据?
How to get nested "Sequelize" data?
我已经创建了一个基于 PostgreSQL 数据库的 Sequelize ORM。我在 product
和 reviews
之间实现了一些关系。而且,每个 review
都由 user
发布。因此,当我查询单个产品时,我想要 product
、reviews
和 review
内的数据,我想查看谁发布的以及 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
}
]
}
这里,“userId”是注册的user
id 的外键。我也想在“评论”中查看用户数据。我该怎么做?
以上JSON数据是通过查询以下代码得到的
Product.findOne({
include: [Review],
where: { id: req.params.id },
})
如果您已经有了像 Review.belongsTo(User, ...
这样的关联定义,那么您只需要用 User
模型指示一个嵌套的 include
选项:
Product.findOne({
include: [{
model: Review,
include: [{
model: User
}]
}],
where: { id: req.params.id },
})
我已经创建了一个基于 PostgreSQL 数据库的 Sequelize ORM。我在 product
和 reviews
之间实现了一些关系。而且,每个 review
都由 user
发布。因此,当我查询单个产品时,我想要 product
、reviews
和 review
内的数据,我想查看谁发布的以及 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
}
]
}
这里,“userId”是注册的user
id 的外键。我也想在“评论”中查看用户数据。我该怎么做?
以上JSON数据是通过查询以下代码得到的
Product.findOne({
include: [Review],
where: { id: req.params.id },
})
如果您已经有了像 Review.belongsTo(User, ...
这样的关联定义,那么您只需要用 User
模型指示一个嵌套的 include
选项:
Product.findOne({
include: [{
model: Review,
include: [{
model: User
}]
}],
where: { id: req.params.id },
})