0

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?

0

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

could you take a look please stackoverflow.com/questions/66210852/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.