当父母登录应用程序时,会出现一个表格,您可以在其中添加一个孩子。我正在尝试将外键分配给要添加子项的父项,但不太确切地知道如何执行此操作。我尝试将外键分配给“ 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;
最佳答案
我正在尝试将外键分配给要添加孩子的父母,但不确定如何做到这一点foreignKey
中的create
应该是parent_id
。
还要确保在父模型中列出了foreignKey
。
这是一个最小的示例:
parent.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')
})
})
})