使用Ember数据保存嵌套模型 [英] Save nested models using Ember Data
问题描述
我在Ember中有两个模型:
I have two models in Ember:
收藏
export default DS.Model.extend({
name: DS.attr(),
description: DS.attr(),
items: DS.hasMany('collection-item')
});
收集项
export default DS.Model.extend({
date: DS.attr(),
volume: DS.attr(),
sequenceNumber: DS.attr()
});
我想将集合项保存在集合的'items'属性内,例如MongoDB:
I want to save the collection items inside the 'items' attribute of the collection, like MongoDB:
[{
"name": "First Collection",
"description": "This is my first collection",
"items": [
{
"date": "2017-07-26",
"volume": "1",
"sequenceNumber": "1"
},
{
"date": "2017-07-27",
"volume": "1",
"sequenceNumber": "2"
}
]
},
{
"name": "Second Collection",
"description": "This is my second collection",
"items": [
{
"date": "2017-07-26",
"volume": "1",
"sequenceNumber": "1"
},
{
"date": "2017-07-27",
"volume": "1",
"sequenceNumber": "2"
}
]
}]
我读过一些有关序列化程序的文章,但我不明白这一点;)有人可以给我一个提示吗?
I have read something about serializers, but I don't get the point ;) Can someone give me a hint?
顺便说一句,我现在正在使用Firebase(emberfire),但将来我将构建自己的API。
BTW, I'm using Firebase (emberfire) for now, but I'm going to build my own API in future.
推荐答案
您所描述的内容在Ember中被称为嵌入式记录。在序列化程序页面上,在JSONAPISerializer讨论的下面是嵌入式记录混合的讨论: https://guides.emberjs.com/v2.14.0/models/customizing-serializers/
What you're describing is known as an embedded record in Ember. On the serializers page, beneath the discussion of the JSONAPISerializer is a discussion of the embedded record mixin: https://guides.emberjs.com/v2.14.0/models/customizing-serializers/
您可以将RESTSerializer与嵌入式mixin实现您的追求。
You can use a RESTSerializer with an embedded mixin to achieve what you're after.
也就是说,除非您的后端需求非常简单,否则建议您在构建后端之前就开始构建后端(并使用JSON-API)。 JSON-API是基于整个Ember社区多年来感受到的痛点的规范。如果您现在构建一个简单的后端,那么将来可能会感到头疼,因为JSON-API是专门为解决这一问题而设计的。
That said, unless your backend needs are fairly simple, I'd suggest beginning to build a backend (and using JSON-API for it) before you get too far. JSON-API is a spec based off of pain points the entire Ember community has felt over the years. If you build a simpler backend right now, you may find yourself hitting headaches in the future that JSON-API is specifically designed to address.
祝你好运!
这篇关于使用Ember数据保存嵌套模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!