Sequelize -在模型创建后检索关联



我正在通过一个关系创建一个模型,我想知道是否有可能在模型的返回中获得这个关系。

公司模型
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"
}
}

有可能吗?

因为您没有将公司数据附加到结果JSON数据结构中,所以您只获得流数据。要得到预期的结果,请尝试修改JSON结构如下:

flow.company = company;

就在return res.json(flow)之前。