这个问题是关于续集查询的。查询具有多对多关系的三个表。以下查询:
const data = await product.findOne ({
where: { product_id: id },
include: [
{
model: category
}
]
});
它返回以下json数据:
"category": {
"product_id": 1,
"name": "Arc d'Triomphe",
"description": "This beautiful and iconic T-shirt will no doubt lead you to your own triumph.",
"price": "14.99",
"discounted_price": "0.00",
"image": "arc-d-triomphe.gif",
"image_2": "arc-d-triomphe-2.gif",
"thumbnail": "arc-d-triomphe-thumbnail.gif",
"display": 0,
"categories": [
{
"category_id": 1,
"name": "French",
"description": "The French have always had an eye for beauty. One look at the T-shirts below and you'll see that same appreciation has been applied abundantly to their postage stamps. Below are some of our most beautiful and colorful T-shirts, so browse away! And don't forget to go all the way to the bottom - you don't want to miss any of them!",
"department_id": 1,
"product_category": {
"product_id": 1,
"category_id": 1
}
}
]
}
我想使上面的json数据如下。如何查询?
"category": [
{
"category_id": 1,
"name": "French",
"department_id": 1
}
]
如果需要模型文件,可以给我评论吗?
答案 0 :(得分:0)
您可以在此document上找到属性。我们有这样一个简单的代码:
const data = await product.findOne ({
where: {product_id: id},
include: [
{
model: category,
attributes: ['category_id', 'name', 'department_id']
}
]
});
答案 1 :(得分:0)
查询如下所示:
const query = await product.findOne({
where: { product_id: id },
include: {
model: category,
attributes: ['category_id', 'name', 'department_id'],
through: { attributes: [] }
},
attributes: []
});
显示以下json数据:
"category": {
"categories": [
{
"category_id": 1,
"name": "French",
"department_id": 1
}
]
}
关键点是through: { attributes: [] }
。