【问题标题】:How to assign foreign key of parent_id to a post route when creating a new child创建新孩子时如何将 parent_id 的外键分配给 post 路由
【发布时间】:2018-08-15 02:43:26
【问题描述】:

当父母登录应用程序时,您可以在其中添加孩子的表单。我正在尝试将外键分配给正在添加孩子的父级,但不太确定如何执行此操作。我尝试将外键分配给“parent_id”,然后在帖子中调用它,但出现此错误:

未处理的拒绝 SequelizeDatabaseError: 字段 'ParentId' 没有默认值

这是我的孩子模型:

module.exports = function (sequelize, DataTypes) {
  var Child = sequelize.define("Child", {
    name: {
      type: DataTypes.STRING,
      allowNull: false
    }
  });

  Child.associate = function(models) {
      Child.belongsTo(models.Parent, {
      foreignKey: "parent_id"
    });
  };

  return Child;
}

这是“添加子”表单的路由

app.get("/addChild", function (req, res) {
    res.render("addChild");
  });

app.post("/addChild", function (req, res) {
    console.log(req.body);
    db.Child.create({
      name: req.body.childName,
      foreignKey: req.body.parent_id 
    }).then(function(data) {
      console.log(data);
      res.json(data);
    });
  });

我在我的 index.js 中使用它。方言:mysql 和 "mysql2": "^1.5.2"

'use strict';

var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config/config.json')[env];
var db = {};

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  var sequelize = new Sequelize(config.database, config.username, 
config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(function (file) {
    return (file.indexOf('.') !== 0) && (file !== basename) && 
(file.slice(-3) === '.js');
  })
  .forEach(function (file) {
    var model = sequelize['import'](path.join(__dirname, file));
     db[model.name] = model;
  });

Object.keys(db).forEach(function (modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
   }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

【问题讨论】:

  • 您是否尝试将create 函数中的foreignKey 替换为parent_id
  • 所以看起来像这样---- parent_id: req.body.parent_id?我得到同样的错误。
  • 我仍然遇到同样的错误。我是否必须像在孩子中那样在我的父模型中做任何关联?像 hasMany 一样?
  • 如果可以的话,试试Child.belongsTo(models.Parent),不要使用foreignKey,然后在createParentId: req.body.parent_id。如果这不起作用,则需要解决某个更深层次的错误。
  • 所以你的意思是这样的:app.post("/addChild", function (req, res) { db.Child.create({ name: req.body.childName, ParentId: req. body.parent_id }).then(function(data) { console.log(data); res.json(data); }); });

标签: javascript node.js express sequelize.js


【解决方案1】:

我正在尝试将外键分配给添加孩子的父级,但不太确定如何执行此操作

create 中的foreignKey 应该是parent_id。 还要确保 foreignKey 列在父模型中。

这是一个最小的例子:

父.js:

module.exports = (sequelize, DataTypes) => {
  var Parent = sequelize.define('Parent', {
    name: DataTypes.STRING
  }, {})
  Parent.associate = function (models) {
    Parent.hasMany(models.Child, {
      foreignKey: 'parent_id' // note foreignKey added
    })
  }

  return Parent
}

child.js:

module.exports = (sequelize, DataTypes) => {
  var Child = sequelize.define('Child', {
    name: DataTypes.STRING
  }, {})
  Child.associate = function (models) {
    Child.belongsTo(models.Parent, {
      foreignKey: 'parent_id'
    })
  }
  return Child
}

工作规格:

const httpMocks = require('node-mocks-http')
const assert = require('assert')
const db = require('../models')

// mocking your /addChild route handler
async function AddChild (req, res, next) {
  const child = await db.Child.create({
    name: req.body.childName,
    parent_id: req.body.parent_id  // parent_id not foreignKey
  })

  res.send(child.toJSON())
}
.
.
.
describe('Test Case', function () {
    it('Associates', async function () {
      const parent = await db.Parent.create({ name: 'Parent' })

      // mock request with body
      const req = httpMocks.createRequest({
        body: {
          childName: 'child',
          parent_id: parent.id
        }
      })

      let res = httpMocks.createResponse()
      await AddChild(req, res)
      assert(res._getData().parent_id === parent.id)

      // ensure association exists as expected
      await parent.reload({
        include: [{
          model: db.Child
        }]
      })
      assert(parent.Children[0].name === 'child')
    })
  })
})

【讨论】:

    猜你喜欢
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    相关资源
    最近更新 更多