1

我有一个 Post 实体:

export class Post {
  @PrimaryKey()
  _id!: ObjectId;

  @Field(() => ID)
  @SerializedPrimaryKey()
  id!: string;

  @Field(() => String)
  @Property()
  createdAt: Date = new Date();

  @Field(() => String)
  @Property({ onUpdate: () => new Date() })
  updatedAt: Date = new Date();

  @Field(() => String)
  @Property()
  title!: string;

  @Field(() => String)
  @Property()
  excerpt!: string;

  @Field(() => String)
  @Property()
  content!: string;

  @Field(() => User)
  @ManyToOne()
  author!: User;
}

用户实体:

@ObjectType()
@Entity()
export class User {
  @PrimaryKey()
  _id!: ObjectId;

  @Field(() => ID)
  @SerializedPrimaryKey()
  id!: string;

  @Field(() => String)
  @Property()
  createdAt = new Date();

  @Field(() => String)
  @Property({ onUpdate: () => new Date() })
  updatedAt = new Date();

  @Field(() => String)
  @Property()
  name!: string;

  @Field(() => String)
  @Property({ unique: true })
  email!: string;

  @Property()
  password!: string;

  @Field(() => [Post], { nullable: true })
  @OneToMany(() => Post, (post) => post.author)
  posts = new Collection<Post>(this);
}

创建帖子功能:

 @Mutation(() => Post)
  async createPost(
    @Arg("post") post: PostInput,
    @Ctx() { em, req }: appContext
  ) {
    const newPost = em.create(Post, {
      ...post,
      author: new ObjectId(req.session.sid),
    });
    await em.persistAndFlush(newPost);
    return newPost;
  }

如您所见,User 和 Post 分别与一对多关系相关。user.posts工作正常,因为我们需要添加init(). 但是当我尝试登录时post.author,它给了我以下信息:

Ref<User> { _id: ObjectId('600663ef9ee88b1b9c63b275') }

我搜索了文档,但找不到如何填充作者字段。

4

1 回答 1

2

要填充关系,您可以使用wrap帮助器:

await wrap(newPost.author).init();

如果实体已经加载,将其标记为已填充就足够了:

await wrap(newPost.author).populated();

(但这里它没有加载,你可以通过Ref<>记录它来判断,它仅用于未加载的实体)

https://mikro-orm.io/docs/entity-helper/#wrappedentity-and-wrap-helper

如果您希望加载的实体和新持久的实体具有相同的结果,您可以populateAfterFlush: true在 ORM 配置中使用。这样,所有关系都将在调用后填充em.flush()。但这在这里也无济于事,因为您正在使用未加载的现有实体的 PK(例如,在使用时会有所帮助newPost.author = new Author())。

顺便说一句,这里不需要使用对象 id,这也应该没问题:

    const newPost = em.create(Post, {
      ...post,
      author: req.session.sid,
    });
于 2021-01-19T12:39:15.727 回答