gpt4 book ai didi

javascript - 创建新子级时如何将parent_id的外键分配给post路由

转载 作者:太空宇宙 更新时间:2023-11-03 22:24:10 26 4
gpt4 key购买 nike

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

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

这是我的 child 模型:

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;

最佳答案

I'm trying to assign the foreign key to the parent that is adding a child but not too sure exactly how to do this

create 中的

foreignKey 应为 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')
})
})
})

关于javascript - 创建新子级时如何将parent_id的外键分配给post路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49144431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com