[英]How to bring all columns in a single row when using include in sequelize.js?
I want to construct query column in a single row. 我想在单行中构造查询列。 I have used the below code in sequelize. 我在续集中使用了以下代码。 Kindly help me to solve this. 请帮助我解决这个问题。
return Entity.userAddress.findAll({
where: {
'user_id': userAddress.user_id
},
include:[{
model: Entity.masterCountry,
required: true,
attributes: ['country_id', 'country_name'],
nested: true
},
{
model: Entity.masterState,
required: true,
attributes: ['state_id', 'state_name']
}]
})
.then((roleList) => {
return roleList;
})
This is my result when I have used above code.
<pre>
{
"code": 0,
"status": "success",
"data": [
{
"user_address_id": "04cec50e-4a2f-445f-b728-5ec8e914e322",
"user_id": "657d1823-1601-4072-863e-fd878f517d66",
"address1": "test1",
"address2": "test2",
"city_name": "chennai",
"masterState": {
"state_id": "b20dd34e-999e-445a-9b90-60246eefbd7e",
"state_name": "Alabama",
"short_name": "AL",
},
"masterCountry": {
"country_id": "aa656249-e0cf-4b40-ac35-8a5672475670",
"country_name": "United States"
}
}
]
}
</pre>
Expected Results should be like the below. 预期结果应如下所示。 Kindly help to me solve this. 请帮助我解决这个问题。
{ "code": 0, "status": "success", "data": [ { "user_address_id": "04cec50e-4a2f-445f-b728-5ec8e914e322", "user_id": "657d1823-1601-4072-863e-fd878f517d66", "address1": "test1", "address2": "test2", "city_name": "chennai", "short_name": "AL" "country_id": "aa656249-e0cf-4b40-ac35-8a5672475670", "country_name": "United States" } ] }
You need to use sequelize.literal
for this, in order to especify the "select" part of the query as you want. 为此,需要使用sequelize.literal
,以便根据需要指定查询的“选择”部分。
return Entity.userAddress.findAll({
where: {
'user_id': userAddress.user_id
},
attributes: [
// your order attributes from userAddress here
[db.sequelize.literal('"masterCountry"."country_id"'), 'country_id'],
[db.sequelize.literal('"masterCountry"."country_name"'), 'country_name'],
[db.sequelize.literal('"masterState"."state_id"'), 'state_id'],
[db.sequelize.literal('"masterState"."state_name"'), 'state_name'],
],
include:[{
model: Entity.masterCountry,
required: true,
attributes: [],
nested: true
},
{
model: Entity.masterState,
required: true,
attributes: []
}]
})
.then((roleList) => {
return roleList;
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.