【问题标题】:Sequelize - Retrieve association after model creationSequelize - 创建模型后检索关联
【发布时间】: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


    【解决方案1】:

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

    flow.company = company;
    

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

    【讨论】:

    • 这个方法不行,还是只接收流对象
    猜你喜欢
    • 2019-12-12
    • 2020-08-25
    • 2016-11-02
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多