这只是一个例子,我知道您通常会有多个评论,但为了这个例子,我们假设我们有
以下型号:
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()
.
最佳答案
这是一种方法:
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
如果您单击“数据库”选项卡,然后单击“评论”,您应该会看到引用 blog-post:1
的多态 ID。
您还可以向 /blog-posts
发送 GET,您应该会看到包含评论,或者向 /comments
发送 GET 并看到多态 可评论
包括在内。
关于javascript - 如何在 Mirage js 中为具有多态一对一关系的模型提供种子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62556674/