在sequelize.js中使用include时,如何将所有列放在一行中?

时间:2019-02-15 03:41:45

标签: node.js sequelize.js hapijs

我想在单行中构造查询列。我在续集中使用了以下代码。请帮助我解决这个问题。

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>

预期结果应如下所示。请帮助我解决这个问题。     

    {
        "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"
            }
        ]
    }
    

1 个答案:

答案 0 :(得分:0)

为此,您需要使用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;
    })