Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

224
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda