乐闻世界logo
搜索文章和话题

如何在 TypeORM 中使用 SELECT 值进行 INSERT

4 个月前提问
3 个月前修改
浏览次数50

1个答案

1

在TypeORM中执行INSERT操作时使用SELECT语句来提供要插入的值,你需要进行一个QueryBuilder操作,这样可以构建出基于某些条件或者动态数据的INSERT语句。以下是一个简单的例子来展示如何在TypeORM中结合INSERTSELECT

假设我们有两个实体UserProfile,现在我们想将一些用户的选定信息(如id)作为外键插入到Profile表中。

首先,你需要确保你的UserProfile实体已经正确定义并且关联好了。

typescript
import { Entity, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn, } from 'typeorm'; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; @OneToOne(() => Profile) @JoinColumn() profile: Profile; } @Entity() export class Profile { @PrimaryGeneratedColumn() id: number; @Column() userId: number; }

假设我们现在想要把所有名字为'Alice'的用户的id插入到Profile表中。

这是如何使用QueryBuilder执行操作的:

typescript
import { getRepository } from 'typeorm'; async function insertProfileForUser() { const userRepository = getRepository(User); const profileRepository = getRepository(Profile); await profileRepository .createQueryBuilder() .insert() .into(Profile) .values( userRepository .createQueryBuilder() .select("user.id", "userId") .from(User, "user") .where("user.name = :name", { name: 'Alice' }) ) .execute(); }

在这个例子中,我们首先获取了UserProfile的仓库,然后创建了一个新的QueryBuilder来进行INSERT操作。values方法中我们传入了另一个QueryBuilder实例,它负责从User表中SELECT出名字为Alice的用户的id字段。注意,我们通过.select("user.id", "userId")别名userId确保了SELECT语句的结果可以和Profile表中的userId字段对应起来。

在构建这样的查询时,务必确保你的SELECT语句返回的列与你INSERT到的表的列匹配。在实际应用中,还需要考虑事务管理、错误处理和性能优化等因素。如果你在具体的应用场景中有特定的需求,可以根据需求调整上述的基本示例来满足你的要求。

2024年6月29日 12:07 回复

你的答案