根据关系在数据库中插入数据 [英] Insert data in database depending by relation

查看:52
本文介绍了根据关系在数据库中插入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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",
  },
  ...
  ]
}

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

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

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

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?

推荐答案

如果你已经在使用查询构建器因为效率而你知道 carId,你应该直接将对象插入 CarsColors:

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

这篇关于根据关系在数据库中插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆