如何在创建新子项时将parent_id的外键分配给后期路由

时间:2018-03-07 04:57:56

标签: javascript node.js express sequelize.js

当父母签到应用程序时,有一个表单可以添加孩子。我试图将外键分配给添加子项的父项,但不太确定如何执行此操作。我尝试将外键分配给" 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;

1 个答案:

答案 0 :(得分:0)

  

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

create中的

parent_id应为foreignKey。 还要确保在父模型中列出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 }

这是一个最小的例子:

parent.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
}

child.js:

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')
    })
  })
})

工作规范:

weight_map = dict(zip(zip(source, target), weight))
weight_map.update(zip(zip(target, source), weight))
data = graph_renderer.edge_renderer.data_source.data
data["line_width"] = [weight_map[edge] * 10 for edge in zip(data["start"], data["end"])]
graph_renderer.edge_renderer.glyph.line_width = {'field': 'line_width'}