Search code examples
postgresqlnestjstypeorm

Insert data in database depending by relation


I am using typeorm, Nest Js and postgresql database. I have the next entities:

import {Entity, Column, PrimaryGeneratedColumn, OneToMany, ManyToOne, JoinColumn, OneToOne} from 'typeorm';
import {User} from "./user.entity";
import {MetaImages} from "./meta-images.entity";

@Entity()
export class Cars {
    @PrimaryGeneratedColumn({name: "carId"})
    carId: number;

    @OneToMany(() => CarsColors, c => c.carId, { cascade: true })
    carsColors: CarsColors[];
}


/// Colors Entity

@Entity()
export class CarsColors {
    @PrimaryGeneratedColumn()
    id: number;

    @Column({ nullable: true})
    color: string;

    @ManyToOne(() => Cars, cars => cars.carId)
    @JoinColumn({ name: 'carId' })
    carId: Cars;
}

The idea of these entities is that i should get something like this:

{
  id: 1,
  carColors: [
  {
    id: 1,
    carId: 1,
    color: "red",
  },
  {
    id: 2,
    carId: 1,
    color: "blue",
  },
  ...
  ]
}

So, each car can have multiple colors. I want, depending by carId to add a new color in CarsColors entity. For this i do:

await getConnection()
  .createQueryBuilder()
  .where("carId = :carId", {
    carId: 1
  })
  .insert()
  .into(MetaImages)
  .values([{
    color: 'new color',
  }])
  .execute();

Doing this, the new color is inserted in the db, but without carId, which is null, so the: .where("carId = :carId", { carId: 1 })
does not work. Question: How to add new color depending by carId?


Solution

  • If you're already using query builder because of efficiency and you know carId, you should insert object directly into CarsColors:

    await getConnection()
      .createQueryBuilder()
      .insert()
      .into(CarsColors)
      .values([{
        carId: 1,
        color: 'new color',
      }])
      .execute();