【发布时间】: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