Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

226
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda