I have 2 entities location and category, location have a manyToOne relation with category i want to know how when i create a location if the categoryid not exist in the category table how i can create a new category with default value.
id do this function
async createLocation(location: LocationI): Promise<LocationI> {
const category = await this.categoryRepository.findOne(location.id);
if (!category) {
this.categoryRepository.save(
this.categoryRepository.create({
name: 'new Category',
description: 'new drestription',
}),
);
}
return await this.locationRepository.save(
this.locationRepository.create(location),
);
}
but when i create a location with a categoryId not referenced on category table i got this error: insert or update on table "location" violates foreign key constraint "FK_53c8ba3797782997cba153c2564"
entities:
@Entity()
export class Location {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@Column()
description: string;
@Column()
location: string;
@Column()
picture: string;
@Column()
stars: number;
@Column({ type: 'integer', name: 'number_of_rooms' })
numberOfRooms: number;
@Column()
price: number;
@Column({ type: 'integer', name: 'category_id' })
categoryId: number;
@ManyToOne(() => Category, (cat) => cat.name)
@JoinColumn({ name: 'category_id', referencedColumnName: 'id' })
category: Category;
}
Category:
@Entity()
export class Category {
@PrimaryGeneratedColumn()
id: number;
@Column({ type: 'text', name: 'name', unique: true })
name: string;
@Column()
description: string;
@OneToMany(() => Location, (location) => location.category)
@JoinColumn({ name: 'location_id', referencedColumnName: 'id' })
locations: Location[];
}