键正在返回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,请参阅下面的评论。