我的项目有一个用户,而该用户有一个联系人。
因此,我正在使用belongsTo
和HasOne
。当我运行代码时,我的联系表将使用外键列创建,但是当我输入信息时,我的foreignKey列将显示“ NULL”。
db.js
db.sequelize = sequelize
db.Sequelize = Sequelize
db.Users = require('../model/User.js')(sequelize, Sequelize);
db.Contacts = require('../model/Contact.js')(sequelize, Sequelize);
db.Contacts.belongsTo(db.Users, { foreignKey: 'fk_user_id', targetKey: 'user_id'});
db.Users.hasOne(db.Contacts, {foreignKey: 'fk_user_id', targetKey: 'user_id'})
sequelize.sync().then(function() {
console.log("Database Connection Succeful");
}, function(err) {
console.log(err);
})
module.exports = db
(型号)
User.js
const Sequelize = require('sequelize')
const db = require("../database/db.js")
module.exports = (sequelize, Sequelize) => {
const Users = sequelize.define('users', {
user_id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
email: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
}
},
{
timestamps: false
});
return Users
}
Contact.js
module.exports = (sequelize, Sequelize) => {
const Contact = sequelize.define('profile_contacts', {
ID: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
phone: {
type: Sequelize.STRING
},
linkedin_profile: {
type: Sequelize.STRING
}
},
{
timestamps: false
});
return Contact
}