我正在使用nodejs的sequelize作为RESTful API。我有2个型号,安全和订单。订单模型通过符号使用外键引用安全模型。
安全模式:
classMethods: {
associate: function(models) {
// associations
security.hasMany(models.order, { foreignKey: 'security_symbol' });
}
}
订单型号:
classMethods: {
// associations
associate: function(models) {
order.belongsTo(models.security, { foreignKey: 'security_symbol' })
}
}
然后我执行一个查询以返回所有正常工作的订单,不过我希望安全模型的其他一些属性包含在一种“平坦的”中。 JSON。 的查询:
Order.findAndCountAll({
where: { user_id: user.id},
attributes: [
'id', 'side', 'quantity', 'price', 'status', 'created_at'
],
order: [
['id', 'DESC']
],
include: [{ model: models.security, attributes: ['name', 'symbol'] }]
})
响应:
"orders": [
{
"id": 25,
"side": 1,
"quantity": 1150,
"price": "13.33",
"status": 0,
"created_at": "2017-04-27T09:51:41.479Z",
"security": {
"name": "Car & General (K) Ltd",
"symbol": "C&G"
}
},
{
"id": 24,
"side": 1,
"quantity": 1000,
"price": "5.63",
"status": 4,
"created_at": "2017-04-27T09:50:31.939Z",
"security": {
"name": "Eveready East Africa Ltd",
"symbol": "EVRD"
}
}...
期望回复:
"orders": [
{
"id": 25,
"side": 1,
"quantity": 1150,
"price": "13.33",
"status": 0,
"created_at": "2017-04-27T09:51:41.479Z",
"security_name": "Car & General (K) Ltd",
"security_symbol": "C&G"
},
{
"id": 24,
"side": 1,
"quantity": 1000,
"price": "5.63",
"status": 4,
"security_name": "Eveready East Africa Ltd",
"security_symbol": "EVRD"
"created_at": "2017-04-27T09:50:31.939Z",
}...
差异是父母的'没有嵌套在订单中。
答案 0 :(得分:3)
您可以使用下面的raw
属性
Order.findAndCountAll({
where: { user_id: user.id},
attributes: [
'id', 'side', 'quantity', 'price', 'status', 'created_at'
],
order: [
['id', 'DESC']
],
include: [{ model: models.security, attributes: ['name', 'symbol'] }]
raw: true
})
但是sequelize会给你带来像
的结果"orders": [
{
"id": 25,
"side": 1,
"quantity": 1150,
"price": "13.33",
"status": 0,
"created_at": "2017-04-27T09:51:41.479Z",
"security.name": "Car & General (K) Ltd",
"security.symbol": "C&G"
},
{
"id": 24,
"side": 1,
"quantity": 1000,
"price": "5.63",
"status": 4,
"security.name": "Eveready East Africa Ltd",
"security.symbol": "EVRD"
}...
我不确定security.name
& security.symbol
是否可取。但这就是续集会表现的方式。希望这有帮助
答案 1 :(得分:0)
尝试以下操作:
Order.findAndCountAll({
where: { user_id: user.id},
attributes: [
'id', 'side', 'quantity', 'price', 'status', 'created_at',
[sequelize.literal('"order->security".name'), 'security_name'],
[sequelize.literal('"order->security".symbol'), 'security_symbol']
],
order: [
['id', 'DESC']
],
include: [{ model: models.security, attributes: []}]
})
请注意,您可能需要将order->security
更新为实际的数据库表名称(orders
和securities
)