Insert data in database depending by relation

徘徊边缘 提交于 2021-02-11 12:28:00

问题


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?


回答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();


来源:https://stackoverflow.com/questions/65967969/insert-data-in-database-depending-by-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!