Reputation: 167
I have a model SKUValue and it is associated with two other models VariantOptions and ProductVariant. I created a sequelize query that "left-joins" SKUValue value with VariantOptions and ProductVariant, and brings brings result.
Sequelize query
await SKUValue.findAll({
where: {
productId: '7bde8a1d-5f6c-4349-bfda-428399c88291'
},
include: [
{
model: VariantOption,
attributes: ['name']
},
{
model: ProductVariant,
attributes: ['name']
}
],
attributes: ['SKUId']
});
The query result returns an array where the attributes VariantOption and ProductVariant are a nested object and has only one field.
[
{
"SKUId": "72edd3ca-fa12-4234-ba8c-dd008eb416d5",
"VariantOption": {
"name": "Large"
},
"ProductVariant": {
"name": "Size"
}
},
{
"SKUId": "72edd3ca-fa12-4234-ba8c-dd008eb416d5",
"VariantOption": {
"name": "Red"
},
"ProductVariant": {
"name": "color"
}
}
]
How do I query the attributes in such a way the result of VariantOption and ProductVariant does not return a nested object but only a stirng.
In general I want the result to be something like this
[
{
"SKUId": "72edd3ca-fa12-4234-ba8c-dd008eb416d5",
"VariantOption.name": "Large",
"ProductVariant.name": "Size"
},
{
"SKUId": "72edd3ca-fa12-4234-ba8c-dd008eb416d5",
"VariantOption.name": "Red",
"ProductVariant.name": "Color"
}
]
Upvotes: 5
Views: 5383
Reputation: 167
I have found the answer to my question.
Using Sequelize.literal, we can easily add the inner attributes in the outer attributes.
return await SKUValue.findAll({
where: {
productId: '7bde8a1d-5f6c-4349-bfda-428399c88291'
},
include: [
{
model: VariantOption,
attributes: []
},
{
model: ProductVariant,
attributes: []
}
],
attributes: [
'SKUId',
[Sequelize.literal('"ProductVariant"."name"'), 'productVariant'],
[Sequelize.literal('"VariantOption"."name"'), 'variantOption']
]
});
Upvotes: 8