【问题标题】:Sequelize one to many association续集一对多关联
【发布时间】:2017-08-16 22:51:01
【问题描述】:

我正在尝试通过参考 sequelize 文档来映射 sequelize 一对多关联,但我无法找到一个完整的示例来使其工作。

我有一个 ClaimType 模型如下

const Sequelize = require('sequelize');

module.exports = function (sequelize) {
    const ClaimType = sequelize.define('claim_type', {
        id: {
            type: Sequelize.INTEGER,
            autoIncrement: true,
            primaryKey: true
        },
        name: {
            type: Sequelize.STRING
        }
    }, {
            timestamps: false,
            freezeTableName: true
        });

    return ClaimType;
};

MaxClaimAmount

const Sequelize = require('sequelize');

module.exports = function (sequelize) {
    const MaxClaimAmount = sequelize.define('max_claim_amount', {
        id: {
            type: Sequelize.INTEGER,
            autoIncrement: true,
            primaryKey: true
        },
        amount: {
            type: Sequelize.DECIMAL
        },
        year: {
            type: Sequelize.INTEGER
        }
    }, {
            timestamps: false,
            freezeTableName: true
        });

    return MaxClaimAmount;
};

终于在index.js

const ClaimType = require('./model/claim_type.js')(sequelize);
const MaxClaimAmount = require('./model/max_claim_amount.js')(sequelize);
ClaimType.hasMany(MaxClaimAmount, { as: 'claimAmount' });

sequelize.sync({ force: false }).then(() => {
            return sequelize.transaction(function (t) {
                return ClaimType.create({
                    name: 'OPD'
                }, { transaction: t }).then(function (claimType) {            
                    // want to know how to associate MaxClaimAmount
                });
            }).then(function (result) {
                sequelize.close();
                console.log(result);
            }).catch(function (err) {
                sequelize.close();
                console.log(err);
            });
        });

ClaimType 对象是从交易的第一部分返回的,我想知道如何实现 ClaimTypeMaxClaimAmount 之间的关联?

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    您在模型中建立关联。

    (关联:sequelize docs 中的一对多)

    const ClaimType = sequelize.define('claim_type', {/* ... */})
    
    const MaxClaimAmount = sequelize.define('max_claim_type', {/* ... */})
    
    ClaimType.hasMany(MaxClaimAmount, {as: 'MaxClaims'})
    

    这会将属性claim_typeIdclaim_type_id 添加到MaxClaimAmount(您将看到该列出现在您的表格中)。 ClaimType 的实例将获得访问器 getMaxClaimssetMaxClaims(因此您可以在表上设置外部 id)

    下一步是创建后端路由并使用访问器实例方法设置外键。访问器函数的调用方式如下:(instance1).setMaxClaims(instance2)

    实例从查询中返回

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-08
      • 2020-02-08
      • 2013-03-23
      • 2014-03-24
      • 1970-01-01
      • 2016-06-13
      • 2017-05-30
      相关资源
      最近更新 更多