简体   繁体   中英

Creating An Association between 2 models In Express-Sequelize MySql

Disclaimer: I am very new to

Node/Express/Sequelize

Questions:

1. Do I need to import visitors.js to visitorsInfo.js so that I can create an association between the 2?

2. If not, how do I set up the visitorsInfo_id as a Foreign Key from visitors.js column visitors_id?

Snippet: ...model/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
        }
    })
}
  1. No need import visitors.js to visitorsInfo.js
  2. Base on the document from Sequelize , In file 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 } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM