问题描述
如何使用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 arrayso 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进行批量插入/更新的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!