我有我的父表“ Users”和子表“ Contacts”。我已经在“联系人”表中添加了外键,以将添加的信息链接回“用户”表。如何在路线中添加它,以便在发布联系人时可以通过邮递员自动创建它。
用户(父表模型)
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
}
fk_user_id: {
type: Sequelize.INTEGER
}
});
return Contact
联系方式(路线)
var express = require("express")
var router = express.Router()
const db = require('../database/db.js');
const Contact = db.Contacts;
var User = db.Users;
// 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)
})
}
})