gpt4 book ai didi

javascript - 在 Express-Sequelize MySql 中创建 2 个模型之间的关联

转载 作者:行者123 更新时间:2023-12-03 22:39:12 26 4
gpt4 key购买 nike

免责声明:我很陌生

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
}
})
}

最佳答案

  • 无需将visitors.js 导入到visitorsInfo.js
  • 基于 Sequelize 的文档,在文件访问者信息.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
    }
  • 关于javascript - 在 Express-Sequelize MySql 中创建 2 个模型之间的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52624638/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com