【问题标题】:Creating An Association between 2 models In Express-Sequelize MySql在 Express-Sequelize MySql 中创建 2 个模型之间的关联
【发布时间】:2018-10-03 10:08:42
【问题描述】:

免责声明:我对

很陌生
Node/Express/Sequelize

问题:

1.是否需要将visitors.js 导入visitorsInfo.js 以便在两者之间建立关联?

2.如果没有,我如何将visitorsInfo_id 设置为visitors.js 列visitors_id 的外键?

片段: ...模型/visitors.js

'use strict'

module.exports = ( sequelize , type ) => {
    return sequelize.define( 'visitors' , {
        visitor_id: {
            type: type.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        web_status: {
            type: type.BOOLEAN
        },
        digital_status: {
            type: type.BOOLEAN
        },
        hosting_status: {
            type: type.BOOLEAN
        },
        training_status: {
            type: type.BOOLEAN
        },
    })
}

.../model/visitors_info.js

'use strict'

module.exports = ( sequelize , type) => {
    return sequelize.define( 'user_info' , {
        visitorsInfo_id: {
            type: type.INTEGER,
            /* 
                How to set up foreign key...?
            */
        },
        firstname: {
            type: type.STRING
        },
        lastname: {
            type: type.STRING
        },
        company: {
            type: type.STRING
        },
        contact_info: {
            type: type.INTEGER
        }
    })
}

【问题讨论】:

    标签: javascript node.js express sequelize.js


    【解决方案1】:
    1. 无需将visitors.js 导入visitorsInfo.js
    2. 基于来自Sequelize的文档,在文件visitorsInfo.js中

      'use strict'
      module.exports = ( sequelize , type) => {
      var user_info = sequelize.define( 'user_info' , {
          visitorsInfo_id: {
              type: type.INTEGER,
          },
          firstname: {
              type: type.STRING
          },
          lastname: {
              type: type.STRING
          },
          company: {
              type: type.STRING
          },
          contact_info: {
              type: type.INTEGER
          }
      });
      
         user_info.associate = function (models) {
           // associations can be defined here
           user_info.belongsTo(models.visitors, {
              as: 'visitors',
              foreignKey: 'visitorsInfo_id',
              targetKey: 'visitor_id'
           });
          }
          return user_info
      }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 2016-11-02
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      相关资源
      最近更新 更多