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;