'"INSERT or UPDATE in table \"devices\" violates foreign key constraint \"devices_typeId_fkey\""

When trying to add an element to the table, the following error occurs: "INSERT or UPDATE in table \"devices\" violates foreign key constraint \"devices_typeId_fkey\"". Why does it occur and how can it be corrected?

Here is my model for the given table in 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},
})

Here I send a request to create fields in the table, and this is where the error comes out

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

Here is the POST request in Postman: enter image description here



Solution 1:[1]

when you insert device you are passing typeId. typeId is a foreign key in Device table which is referenced from Device Type table. there should be a primary key record with the value of typeId in Device Type table.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arun VC