"INSERT or UPDATE in table "设备\ " violates foreign key constraint " devices_typeId_fkey\ "



尝试向表中添加元素时,会出现以下错误:"INSERT or UPDATE in table "devices" violates foreign key constraint "devices_typeId_fkey""。为什么会发生这种情况,如何纠正?

这是sequelize中给定表格的模型。

const Device = sequelize.define('device', {
id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
name: {type: DataTypes.STRING, unique: true, allowNull: false},
price: {type: DataTypes.INTEGER, allowNull: false},
rating: {type: DataTypes.INTEGER, defaultValue: 0},
img: {type: DataTypes.STRING, allowNull: false},
})

在这里,我发送了一个在表中创建字段的请求,这就是出现错误的地方

const uuid = require('uuid')
const path = require('path');
const {Device, DeviceInfo} = require('../models/models')
const ApiError = require('../error/ApiError');
class DeviceController {
async create(req, res, next) {
try {
let {name, price, brandId, typeId, info} = req.body
const {img} = req.files
let fileName = uuid.v4() + ".jpg"
img.mv(path.resolve(__dirname, '..', 'static', fileName))
const device = await Device.create({name, price, brandId, typeId, img: fileName});
return res.json(device)
} catch (e) {
next(ApiError.badRequest(e.message))
}
}

以下是Postman中的POST请求:在此处输入图像描述

当您插入设备时,您正在传递typeId。typeId是Device表中的外键,它是从Device Type表中引用的。设备类型表中应该有一个值为typeId的主键记录。

我也很喜欢UlbiTv教程我也遇到了同样的问题,这就是我找到你的视频的原因

所以问题出在你对数据库的请求上。我已经修复了它,在我的情况下,我在主体中设置了一个不存在的typeId。我没有意识到我的types table开始像"{id: 1, ...} , {id: 6, ...}",但我请求创建一个带有typeId === 2的设备,但我没有这样的id仅此而已。

相关内容

最新更新