Error: The operation performed on the table has violated the foreign key constraint for TelephoneContact

Purpose

Make sure that data is inserted into the telephones table when a new client is created.

Situation

I am working with 3 tables named clients, contacts, and telephones. The relationships between these tables are shown in the diagram. The owner_id can be linked to either contacts.id or clients.id. However, when I attempt to create a new client, the client is created successfully but data is not inserted into the telephones table. Instead, an error is displayed:

{
  "error": "insert or update on table \"telephones\" violates foreign key constraint \"TelephoneContact\""
}

https://i.sstatic.net/thnxJ.png

Migration Process

import {
  MigrationInterface,
  QueryRunner,
  TableColumn,
  TableForeignKey,
} from 'typeorm';

export default class AddOwnerIdToTelephones1597250413640
  implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    // Migration code to add owner_id column and foreign key constraints
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // Migration code to drop foreign key constraints and owner_id column
  }
}

Telephone Model Definition

import {
  PrimaryGeneratedColumn,
  Column,
  Entity,
  ManyToOne,
  JoinColumn,
} from 'typeorm';

import Client from './Client';
import Contact from './Contact';

@Entity('telephones')
class Telephone {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  telephone_number: string;

  // Define the relationships with Client and Contact entities
  @ManyToOne(() => Client, client => client.id)
  @ManyToOne(() => Contact, contact => contact.id)
  @JoinColumn({ name: 'owner_id' })
  owner_id: string;
}

export default Telephone;

Answer №1

It is not possible to create the telephones table as described. Trying to define the column owner_id as a FK to both the contacts table and the clients table is not supported by Postgres. The column can only be a FK to one table at a time. This could lead to FK violations when inserting into clients because the telephone value does not exist in contacts.

There are 3 potential solutions:

  1. Add 2 FK columns in telephone, one for each table. Then, decide if one of them must be null or if they can both be populated.
  2. Reverse the direction of FKs so that both clients and contacts have a FK to telephone. This implies they can both point to the same telephone with ease.
  3. Consider migrating the telephone number to both the clients and contacts tables and eliminate the telephone table altogether. Is there a business reason for segregating telephone numbers? How does the business differentiate telephone numbers from emails?

In the absence of significant business processes relating to telephone numbers, option #3 would be the preferred choice.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to implement debouncing for an editor value that is controlled by the parent component?

Custom Editor Component import Editor from '@monaco-editor/react'; import { useDebounce } from './useDebounce'; import { useEffect, useState } from 'react'; type Props = { code: string; onChange: (code: string) => void ...

React: Issue accessing URL parameters using useParams() within a nested component

In my demo application, there are two components - QuoteDetail and Comments. Both require URL parameters, but I am only able to access them in the parent component. App.tsx: <Switch> // ... <Route path="/quotes" exact> <Al ...

Developing with TypeScript - Utilizing the <reference path="....."> directive

Recently, I encountered an issue while adding a plugin to the TypeScript compiler. After including my code and compiling tsc.ts, it compiled without any errors. However, when I attempted to run it, I noticed that some variables declared in io.ts were missi ...

experimenting with the checked attribute on a radio button with jasmine testing

Currently using Angular 8 with Jasmine testing. I have a simple loop of radio buttons and want to test a function that sets the checked attribute on the (x)th radio button within the loop based on this.startingCarType. I am encountering false and null tes ...

Implementing a boolean toggle method in Typescript for a class property

Hello there, fellow programmers! I am interested in changing the value of a class field using a method. I have a button in Angular that, when clicked, triggers the onSave() method: export class CourseComponent { isActive:boolean; onSave() { ...

Issue encountered when trying to bring in a component from a different module

I am attempting to import the 'OpenDialogContentComponent' component from Module A into Module B, however I am encountering this error: 'Cannot determine the module for class OpenDialogContentComponent in C:/Users/jitdagar/Desktop/TDP/pwt-u ...

Error in Angular 7: ActivatedRoute paramId returns null value

On page load, I am trying to subscribe to my paramsID, but when I use console.log(), it returns null. I am currently working with Angular 7. Here is my TypeScript code: import { Component, OnInit } from '@angular/core'; import { Activat ...

What are the steps for utilizing the watch feature in Vue.js with TypeScript?

Currently, I am looking to convert this JavaScript script into TypeScript. However, I require the syntax for watchers. export default { props: ['branch_id'], watch: {} } ...

Nodemailer fails to display an error message when the email is not successfully sent

I am currently working on implementing nodemailer for sending emails. However, I noticed that if the email address in the "to" field is incorrect, the email is not sent as expected. The issue is that there is no error displayed and the function still resol ...

Discover how to access JSON data using a string key in Angular 2

Trying to loop through JSON data in angular2 can be straightforward when the data is structured like this: {fileName: "XYZ"} You can simply use let data of datas to iterate over it. But things get tricky when your JSON data keys are in string format, li ...

Discover additional features in Angular 4 by reading further

I am struggling with incorporating a "read more" feature in my paragraph on my website. The challenge I'm facing is determining how to trigger the feature to display only when there are more than 5 lines of text. <p>Contrary to popular belief, ...

Guide to sending back an Observable within Angular 4

Inside my authProvider provider class, I have the following method: retrieveUser() { return this.afAuth.authState.subscribe(user => { return user; }); } I am looking to subscribe to this method in a different class. Here is an example ...

My Angular-based todo application has encountered an error notification from the system

Every time I try to post something, the system responds with a 405 error message in the console. I'm not sure what caused this issue or how to resolve it. Alternatively, if I click the done button, the console displays a 500 error message. Here is t ...

Updating the mat-icon in a row when a button is clicked

I am currently working on implementing the mat-table in my project. I am facing an issue where I need to change the mat-icon of a button based on a click event, but I only want this change to apply to a single row in the table. At the moment, I am able to ...

Export an array of objects using the Angular XLSX library

Here is my example data: exampleData: any[] = [ { "id": "123", "requestType": "Demo", "requestDate": "12/05/21", "status": "Success", "product": [ { "productName": "example product A", "productQty": "8" ...

Error TS 2322 - The property 'id' is not present in the object of type '{ id: number'

Just starting out with Angular and TypeScript. I created a model with the same properties but encountered an error and am struggling to find a solution: TS2322: Type '{ id: number; model: string; plate: string; deliveryDate: string; deadline: st ...

Deleting unique constraint from a field in Django

My model looks like this: class LoginAttempts(models.Model): user = models.OneToOneField(User, unique=False) counter = models.IntegerField(null=True) login_timestamp = models.DateTimeField(auto_now=True) When the table is created in the datab ...

In TypeScript, it can be challenging to determine the equality between a value and an enum

I am encountering an issue with my simple code: enum Color { BLUE, RED } class Brush { color: Color constructor(values) { this.color = values.color } } let JSON_RESPONSE = `{"color": "BLUE"}` let brush = new Brush(JSON.parse(JSON ...

The combination of arrays and array methods in intersection types may encounter difficulty in accessing all fields

I have two different types, both in the form of arrays of objects with specified fields, combined into an intersection type in Typescript. When I access an element from the array, I can retrieve the second field without any issues. However, when I try to ...

Tips for Invoking an Overloaded Function within a Generic Environment

Imagine having two interfaces that share some fields and another interface that serves as a superclass: interface IFirst { common: "A" | "B"; private_0: string; } interface ISecond { common: "C" | "D"; private_1: string; } interface ICommo ...