我通过sequelize添加了外键用户是我的父表和联系人ID我的子表外键是user_id,当我发布详细信息时,我希望它在联系人表中将用户ID显示为外键,但它正在显示为空。
用户模型
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
}
});
return Users
}
联系方式
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
}
});
return Contact
}
联系路线
var express = require("express")
var router = express.Router()
const db = require('../database/db.js');
const Contact = db.Contacts;
// get all jobs
router.get("/", (req, res) => {
Contact.findAll()
.then(contacts => {
res.json(contacts)
})
.catch(err => {
res.send('error: ' + err)
})
})
// Add job
router.post("/", (req, res) => {
if(!req.body.phone,
!req.body.linkedin_profile) {
res.status(400)
res.json({
error: "Bad Data"
})
} else {
Contact.create(req.body)
.then(() => {
res.send("Contact Added")
})
.catch(err => {
res.send("Error: " + err)
})
}
})
数据库
const Sequelize = require('sequelize')
const db = {}
sequelize = new Sequelize('database', 'useer' , 'Password' , {
host: 'host',
dialect: 'mysql',
operatorsAliases: false,
dialectOptions: {
ssl: true
},
pool: {
max: 100,
min: 0,
acuire: 3000,
idle: 10000
},
})
sequelize.sync().then(function() {
console.log("Database Connection Succeful");
}, function(err) {
console.log(err);
})
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'})
module.exports = db