如何嵌入具有多对多关系的子数据?
How can I embed child data with many-to-many relationships?
我在 MirageJs 中有两个模型:
- 博客
- 标签
每个博客可以有更多标签,反之亦然。我与一个名为 blog_tag
的连接 table 建立了多对多关系。我的问题是,当我从服务器获得响应时,tags 仅包含 id 属性。我怎样才能将整个标签对象嵌入到响应中?
Response:
{
"blogs": [
{
"title": "Some title",
"author": "Author 0",
"id": "1",
"tags": [
{
"id": "1"
// Other properties are not included here :(
}
]
}
]
}
I like to see something like this:
{
"blogs": [
{
"title": "Some title",
"author": "Author 0",
"id": "1",
"tags": [
{
"id": "1",
"name": "Tag 0"
}
]
}
]
}
我的服务器配置:
Mirage REPL
import { belongsTo, createServer, Factory, hasMany, Model, RestSerializer } from "miragejs"
export default createServer({
serializers: {
blog: RestSerializer.extend({
include: ['tags'],
embed: true
})
},
models: {
blog: Model.extend({
tags: hasMany('blog_tag')
}),
tag: Model.extend({
blogs: hasMany('blog_tag')
}),
blog_tag: Model.extend({
blog: belongsTo(),
tag: belongsTo()
})
},
factories: {
blog: Factory.extend({
author(i) {
return 'Author ' + i
},
title() {
return 'Some title'
}
}),
tag: Factory.extend({
name(i) {
return 'Tag ' + i
}
})
},
seeds(server) {
server.createList('blog', 2)
server.createList('tag', 10)
server.create('blog_tag', { blogId: 1, tagId: 1 })
},
routes() {
this.namespace = "api"
this.get("/blogs", (schema) => {
return schema.blogs.all()
})
},
})
你实际上不需要 blog_tag
模型来做多对多,Mirage.js 只需要 blog
和 tag
模型。
在此处查看工作示例:Mirage REPL
我在 MirageJs 中有两个模型:
- 博客
- 标签
每个博客可以有更多标签,反之亦然。我与一个名为 blog_tag
的连接 table 建立了多对多关系。我的问题是,当我从服务器获得响应时,tags 仅包含 id 属性。我怎样才能将整个标签对象嵌入到响应中?
Response:
{
"blogs": [
{
"title": "Some title",
"author": "Author 0",
"id": "1",
"tags": [
{
"id": "1"
// Other properties are not included here :(
}
]
}
]
}
I like to see something like this:
{
"blogs": [
{
"title": "Some title",
"author": "Author 0",
"id": "1",
"tags": [
{
"id": "1",
"name": "Tag 0"
}
]
}
]
}
我的服务器配置: Mirage REPL
import { belongsTo, createServer, Factory, hasMany, Model, RestSerializer } from "miragejs"
export default createServer({
serializers: {
blog: RestSerializer.extend({
include: ['tags'],
embed: true
})
},
models: {
blog: Model.extend({
tags: hasMany('blog_tag')
}),
tag: Model.extend({
blogs: hasMany('blog_tag')
}),
blog_tag: Model.extend({
blog: belongsTo(),
tag: belongsTo()
})
},
factories: {
blog: Factory.extend({
author(i) {
return 'Author ' + i
},
title() {
return 'Some title'
}
}),
tag: Factory.extend({
name(i) {
return 'Tag ' + i
}
})
},
seeds(server) {
server.createList('blog', 2)
server.createList('tag', 10)
server.create('blog_tag', { blogId: 1, tagId: 1 })
},
routes() {
this.namespace = "api"
this.get("/blogs", (schema) => {
return schema.blogs.all()
})
},
})
你实际上不需要 blog_tag
模型来做多对多,Mirage.js 只需要 blog
和 tag
模型。
在此处查看工作示例:Mirage REPL