sequelize foreign key returning as “Null”

2019-08-29 04:18发布

问题:

I have added foreign keys to my project using sequelize. User is the parent table and profile_personals is the child table. When I post something the foreign key comes out as NULL. I'm trying to create it so when I post something through postman it can grab the User id Automatically.

db.js file

const db = {}; 
db.sequelize = sequelize;
db.Sequelize = Sequelize;

// Models
db.Users = require('../model/User.js')(sequelize, Sequelize);
db.Personal = require('../model/profile_personal.js')(sequelize, Sequelize);


// Foreign Key Connections
db.Personal.belongsTo(db.Users, {foreignKey: 'fk_user_id', targetKey: 'user_id'});
db.Users.hasOne(db.Personal, {foreignKey: 'fk_user_id', targetKey: 'user_id'});

User.js Model

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

profile_personals.js Model

     module.exports = (sequelize, Sequelize) => {
    const Personal = sequelize.define('profile_personals', {
        ID: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        biography: {
            type: Sequelize.STRING
        }
    },
    {
        timestamps: false
    });

    return Personal;
}

Profile_personals.js Route

var express = require("express")
var router = express.Router()
const db = require('../database/db.js');
const Personal = db.Personal;

// get all profile personals
router.get("/", (req, res) => {
    Personal.findAll()
      .then(personals => {
          res.json(personals)
      })
      .catch(err => {
          res.send('error: ' + err)
      })
})


// Add job
router.post("/", (req, res) => {
    if(!req.body.biography) {
        res.status(400)
        res.json({
            error: "Bad Data"
        })
    } else {
       Personal.create(req.body)
        .then(() => {
            res.send("Personal Added")
        })
        .catch(err => {
            res.send("Error: " + err)
        })
    }
})

回答1:

I think your hasOne keys are reversed, give this a try:

db.Users.hasOne(db.Personal, {foreignKey: 'user_id', targetKey: 'fk_user_id'});

FWIW, my preference is to include the FK fields in the data model, for readability... e.g.

const Personal = sequelize.define('profile_personals', {
        ID: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        biography: {
            type: Sequelize.STRING
        },
        fk_user_id : {type: Sequelize.INTEGER},
    },
    {
        timestamps: false
    });