1
我有如下關係:Sequelize許多一對多格式化
var Order = sequelize.define('order', {
id : {
type : Sequelize.INTEGER,
primaryKey : true,
autoIncrement : true
},
amount : { type : Sequelize.DOUBLE },
change : { type : Sequelize.DOUBLE },
status : { type : Sequelize.ENUM('draft', 'placed', 'in_transit', 'fulfilled', 'rejected') },
statusReason : { type : Sequelize.STRING },
address : { type : Sequelize.STRING },
latitude : { type : Sequelize.DOUBLE },
longitude : { type : Sequelize.DOUBLE }
})
var Beverage = sequelize.define('beverage', {
id : {
type : Sequelize.INTEGER,
primaryKey : true,
autoIncrement : true
},
name : { type : Sequelize.STRING },
picture : { type : Sequelize.STRING },
price : { type : Sequelize.DOUBLE },
max : { type : Sequelize.DOUBLE },
})
var OrderBeverage = sequelize.define('orderBeverage', {
id : {
type : Sequelize.INTEGER,
primaryKey : true,
autoIncrement : true
},
orderId : { type : Sequelize.INTEGER },
beverageId : { type : Sequelize.INTEGER },
amount : { type : Sequelize.INTEGER }
})
Order.hasMany(OrderBeverage, { as : 'beverages' })
OrderBeverage.belongsTo(Beverage)
OrderBeverage.belongsTo(Order)
所以,如果我做一個簡單的查詢,包括關係,我有以下的源和結果:
let orders = yield Order.findAll({
include : [{
model : Order.Beverage,
as : 'beverages',
attributes : ['createdAt'],
include : [ Beverage ]
}]
})
以及由此產生的json:
[
{
"id": 2,
"amount": 0,
"change": 0,
"status": "placed",
"statusReason": "wrong address given",
"address": "street x, michigan",
"latitude": 0,
"longitude": 0,
"createdAt": "2016-01-12T22:39:32.000Z",
"updatedAt": "2016-01-13T21:05:06.000Z",
"beverages": [
{
"createdAt": "2016-01-12T23:10:48.000Z",
"beverage": {
"id": 1,
"name": "Vodka",
"picture": "somepic",
"price": 30,
"max": 5,
"createdAt": "2016-01-12T22:26:10.000Z",
"updatedAt": "2016-01-12T22:26:10.000Z"
}
}
]
}
]
我需要使屬性beverages
成爲飲料內容的數組,而不是{ createdAt, beverage }
這個飲料的內容是beverage
密鑰的數組。
最後的結果會是什麼樣子:
[
{
"id": 2,
"amount": 0,
"change": 0,
"status": "placed",
"statusReason": "wrong address given",
"address": "street x, michigan",
"latitude": 0,
"longitude": 0,
"createdAt": "2016-01-12T22:39:32.000Z",
"updatedAt": "2016-01-13T21:05:06.000Z",
"beverages": [
{
"id": 1,
"name": "Vodka",
"picture": "somepic",
"price": 30,
"max": 5,
"createdAt": "2016-01-12T22:26:10.000Z",
"updatedAt": "2016-01-12T22:26:10.000Z"
}
]
}
]
我已經通過文件搜索,但沒有找到它。有任何想法嗎?