将外键返回“ Null”

时间:2019-02-14 15:14:06

标签: mysql node.js foreign-keys sequelize.js postman

我已经使用sequelize将外键添加到了我的项目中。用户是父表,profile_personals是子表。当我发布内容时,外键显示为NULL。我正在尝试创建它,因此当我通过邮递员发布东西时,它可以自动获取用户ID。

enter image description here

db.js文件

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模型

    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模型

     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路线

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 个答案:

答案 0 :(得分:0)

我认为您的hasOne键已反转,请尝试以下操作:

sqrt

FWIW,我更喜欢在数据模型中包含FK字段,以提高可读性...例如

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