Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
typeorm create records if id not found with manytoone relations nestjs

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[];
}
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!