47

据我所知,最好的做法是在更新后退回项目。TypeORM 的updateById返回void,而不是更新的项目。

我的问题:是否可以在一行中更新和返回修改后的项目?

到目前为止我尝试了什么:

await this.taskRepository.updateById(id, { state, dueDate });
return this.taskRepository.findOne({ id });

我在找什么:

return this.taskRepository.updateById(id, { state, dueDate }); // returns updated task
4

4 回答 4

61

我刚刚发现我可以用以下.save方法做到这一点:

return this.taskRepository.save({
    id: task.id,
    state,
    dueDate
});

根据文档(部分save),也支持部分更新:

由于跳过了所有未定义的属性,因此还支持部分更新。

于 2017-12-13T15:44:26.817 回答
23

为了扩展 Sandrooco 的答案,这就是我所做的:

const property = await this.propertyRepository.findOne({
  where: { id }
});

return this.propertyRepository.save({
  ...property, // existing fields
  ...updatePropertyDto // updated fields
});
于 2019-11-08T05:50:38.587 回答
18

键正在返回response.raw[0]以获取类型。


虽然我想await Table.update({}, {})退货Table它没有。我发现使用它更容易,QueryBuilder因为它通常给我更多的控制权,但是如果你不喜欢QueryBuilder 或者不需要它,你可以做这样的事情:

const post = await Post.update({id}, {...input}).then(response => response.raw[0]);
return post; // returns post of type Post

但是,如果您确实想使用,QueryBuilder我建议您采用如下方法。Repository上面的其他人提到了and的用法,Table.save()它并没有真正在type任何地方返回原件,所以这种方法对我来说是不可能的。

一个例子Table.update({}, {})

@Mutation(() => PostResponse, { nullable: true })
@UseMiddleware(isAuthorized)
async updatePost(
  @Arg("id", () => Int) id: number,
  @Arg("input") input: PostInput,
  @Ctx() { req }: Context
): Promise<PostResponse | null> {
  // ...
  const post = await Post.update({id}, {...input}).then(response => response.raw[0]);
  return { post };
}

一个例子QueryBuilder

@Mutation(() => PostResponse, { nullable: true })
@UseMiddleware(isAuthorized)
async updatePost(
  @Arg("id", () => Int) id: number,
  @Arg("input") input: PostInput,
  @Ctx() { req }: Context
): Promise<PostResponse | null> {
  // ...
  const post = await getConnection()
    .createQueryBuilder()
    .update(Post)
    .set({ ...input })
    .where('id = :id and "creatorId" = :creatorId', {
      id,
      creatorId: userId,
    })
    .returning("*")
    .execute()
    .then((response) => {
      return response.raw[0];
    });

  return { post };
}

辅助功能(如果你不想一直写response.raw[0]

const typeReturn = async <T>(mutation: Promise<UpdateResult | DeleteResult | InsertResult>): Promise<T> => {
  return await mutation.then((res) => res.raw[0]);
};

用法:

const update = await typeReturn<Post>(Post.update(...));
const insert = await typeReturn<Attachment>(Attachment.insert(...));
const del    = await typeReturn<User>(User.delete(...));

注意:我在这里使用 TypeORM 和 Type-GraphQL。

.returning("*")不适用于 MySQL,请参阅下面的评论。

于 2020-09-29T09:30:36.887 回答
1

一种方法是执行更新,然后根据您指定的条件进行查找

于 2020-03-18T05:01:21.450 回答