【问题标题】:"INSERT or UPDATE in table \"devices\" violates foreign key constraint \"devices_typeId_fkey\""\"表 \\\"devices\\\" 中的 INSERT 或 UPDATE 违反外键约束 \\\"devices_typeId_fkey\\\"\"
【发布时间】:2022-11-11 03:36:50
【问题描述】:

尝试向表中添加元素时,出现以下错误:"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 请求: enter image description here

【问题讨论】:

  • 这基本上意味着您有一个外键 - 您尝试输入的值在(我猜)types 表中不存在

标签: javascript postgresql


【解决方案1】:

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

【讨论】:

  • 也就是说,我应该在 const Device(我的模型)中添加新字段 typeId、brandId 吗?
  • 是的,你的表必须有这两个字段
  • 我添加了这些字段仍然是同样的错误,也许还有其他原因?我对给定表有依赖关系
【解决方案2】:

)我也很喜欢 UlbiTv 教程) 我有同样的错误,这就是我找到你的视频的方式

所以麻烦在于您对数据库的请求 我已经修好了 就我而言,我在正文中设置了一个不存在的 typeId 我没有抓住我的类型表开始像“{id:1,...},{id:6,...}”的那一刻 但我正在请求创建一个 typeId === 2 的设备,但我没有这样的 id 就这样))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2011-01-27
    相关资源
    最近更新 更多