【发布时间】:2021-05-14 21:28:24
【问题描述】:
我正在通过关系创建模型,我想知道是否可以在模型的返回中获取关系。
公司模式
module.exports = (sequelize) => {
const company = sequelize.define('company', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
uuid: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4
},
name: {
type: DataTypes.STRING,
allowNull: false
}
})
company.hasMany(sequelize.models.flow, {foreignKey: 'company_id', as: 'flows'})
}
流动模型
module.exports = (sequelize) => {
const flow = sequelize.define('flow', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
company_id: {
allowNull: false,
type: DataTypes.INTEGER
},
uuid: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4
},
name: {
type: DataTypes.STRING,
allowNull: false
},
description: {
type: DataTypes.TEXT
}
})
flow.belongsTo(sequelize.models.company, {foreignKey: 'company_id', as: 'company'})
}
查询
const company = await ORM.models.company
.findOne({
where: {
uuid: req.body.company_id
}
})
if (company) {
const flow = await company.createFlow({
name: req.body.name
})
return res.json(flow)
}
我目前收到以下回复:
{
"uuid": "647aa7b2-163a-4bab-80f6-441c9bf29915",
"id": 12,
"name": "Flow 2",
"company_id": 2,
"updated_at": "2021-02-11T06:08:25.160Z",
"created_at": "2021-02-11T06:08:25.160Z",
"description": null
}
我想获得:
{
"uuid":"647aa7b2-163a-4bab-80f6-441c9bf29915",
"id":12,
"name":"Flow 2",
"updated_at":"2021-02-11T06:08:25.160Z",
"created_at":"2021-02-11T06:08:25.160Z",
"description":null,
"company":{
"id":2,
"uuid":"3dea2541-a505-4f0c-a356-f1a2d449d050",
"name":"Company 1",
"created_at":"2021-02-11T05:48:11.872Z",
"updated_at":"2021-02-11T05:48:11.872Z"
}
}
有可能吗?
【问题讨论】:
标签: node.js sequelize.js