2

这只是一个示例,我知道您通常会有多个评论,但是为了这个示例,假设我们有

以下型号:

 models: {
    blogPost: Model.extend({
      comment: belongsTo(),
    }),

    picture: Model.extend({
      comment: belongsTo(),
    }),

    comment: Model.extend({
      commentable: belongsTo({ polymorphic: true }),
    }),
  },

和以下工厂:

  factories: {
    blogPost: Factory.extend({
      title: "Whatever",
      withComment: trait({
        comment: association(),
      }),
  }),

现在,当尝试使用以下内容播种服务器时:

seeds(server) {
  server.create("blogPost", "withComment");
}

它确实播种了它,但是当检查console.log(server.db.dump());可评论为空时commentableId: null...。

在此处输入图像描述

为什么?

编辑:

这是一个棘手的问题。我变了

comment: Model.extend({
  commentable: belongsTo({ polymorphic: true }),
}),

至:

comment: Model.extend({
  blogPost: belongsTo({ polymorphic: true }),
}),

只是看看是否commentable部分导致了问题。这次我得到了一个不同的错误: Mirage: You're using the association() helper on your comment factory for blogPost, which is a polymorphic relationship. This is not currently supported."

因此,目前无法association()在多态关系上使用。我希望这在文档中宣布...

尽管如此,即使没有速记,我也找不到播种的方法association()

4

2 回答 2

2

这是一种方法:

import { Server, Model, Factory, belongsTo, trait, association, RestSerializer } from "miragejs"

export default new Server({
  serializers: {
    blogPost: RestSerializer.extend({
      include: ['comment']
    }),
  },

  models: {
    blogPost: Model.extend({
      comment: belongsTo(),
    }),

    picture: Model.extend({
      comment: belongsTo(),
    }),

    comment: Model.extend({
      commentable: belongsTo({ polymorphic: true }),
    }),
  },
  
  factories: {
    blogPost: Factory.extend({
      title: "Whatever",
      withComment: trait({
        afterCreate(blogPost, server) {
          server.create('comment', {
            commentable: blogPost
          });
        }
      }),
    })
  },

  seeds(server) {
    server.create("blog-post", "withComment");
    console.log(server.db.dump())
  },
  
  routes() {
    this.resource('blog-post')
  }

})

这是有效的 REPL: http: //miragejs.com/repl/v1/144

如果单击 Database 选项卡,然后单击 Comments,您应该会看到多态 ID 引用blog-post:1

您还可以发送 GET 到/blog-posts,您应该会看到包含评论,或者发送 GET 到/comments并查看commentable包含的多态。

于 2020-07-04T21:57:30.603 回答
0

这个特殊的错误:

您在 blogPost 的评论工厂中使用了 association() 助手,这是一种多态关系。目前不支持此功能。”

以这种方式为我解决了:// mirage/factories/comment.js

前:

import { association, Factory } from 'ember-cli-mirage';

export default Factory.extend({
  blogPost: association()

后:

import { association, Factory, trait } from 'ember-cli-mirage';

export default Factory.extend({
  blogPost: trait({
    receiver: 'blogPost',
    blogPost: association()
  }),
于 2020-11-23T12:44:36.293 回答