使用typeORM进行批量插入/更新的有效方法 [英] Efficient way to bulk insert / update using typeORM

查看:3561
本文介绍了使用typeORM进行批量插入/更新的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用TypeORM将预先创建的对象与对象建立关系? 据我所知,效率低下是这样(许多关系很多):

How it's possible to insert pre-created objects into relation with an object using TypeORM? As I know the non-efficient is this(many to many relations):

 const tags = await Tag.findByIds(tagIds);
 const todo = await Todo.findOne(todoId);
 todo.tags = tags;
 return await Todo.save(todo)

RelationalQueryBuilder.add()属性也采用单个对象或ID,如

Also .add() property of RelationalQueryBuilder takes single object or Id as is mentioned in docs

await getConnection()
    .createQueryBuilder()
    .relation(Post, "categories")
    .of(1)
    .add(3);

那么批量插入的有效方法是什么?

So what is the efficient way to bulk insert?

推荐答案

我在使用从typeGraphql导入的@Arg传递字符串数组时遇到了错误,因此我解决了问题,因此从typeOrm提取的add()接受了ID数组 因此,关系查询的快速高效的示例是:

I had error while using @Arg imported from typeGraphql for passing an array of string so I resolved it so add() from typeOrm takes the Id array so the fast and performant example of relational query is:

import { Resolver, Arg, Mutation } from "type-graphql";
import { Todo } from "../../entity/Todo";
import { createQueryBuilder } from "typeorm";

@Resolver()
export class BulkAssignTagsResolver {
  @Mutation(() => Todo)
  async bulkAssignTodoTag(
    @Arg("tagIds", () => [String]) tagIds: string[],
    @Arg("todoId") todoId: string
  ): Promise<Todo | undefined> {
    await createQueryBuilder("todo")
      .relation(Todo, "tags")
      .of(todoId)
      .add(tagIds);

    return Todo.findOne(todoId, { relations: ["tags"] });
  }
}

这篇关于使用typeORM进行批量插入/更新的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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