【问题标题】:Insert data in database depending by relation根据关系在数据库中插入数据
【发布时间】:2021-05-04 04:04:10
【问题描述】:

我正在使用 typeorm、Nest Js 和 postgresql 数据库。 我有下一个实体:

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;
}

这些实体的想法是我应该得到这样的东西:

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

所以,每辆车都可以有多种颜色。我希望根据 carId 在 CarsColors 实体中添加新颜色。 为此,我这样做:

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

这样做,新颜色被插入到数据库中,但没有carId,它是空的,所以: .where("carId = :carId", { carId: 1 })
不起作用。问题:如何根据carId添加新颜色?

【问题讨论】:

    标签: postgresql nestjs typeorm


    【解决方案1】:

    如果您因为效率已经在使用查询生成器并且您知道 carId,则应该将对象直接插入 CarsColors:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    相关资源
    最近更新 更多