对 Ember 数据使用主键 [英] Using primary keys with Ember Data
问题描述
过去几天我一直在苦苦挣扎主键和最新版本的 Ember Data.
I've been struggling for the past few days with primary keys and the last version of Ember Data.
我首先阅读了 GitHub 上的重大更改文件a>,但它显然已经过时了.我尝试了 几个 其他 方法(在 Peter Wagenet 的帮助下IRC),但它们似乎都不起作用.
I first read how to do it on the Breaking Changes file on GitHub, but it's apparently outdated. I tried several other ways (with the help of Peter Wagenet on IRC), but none of them seem to work.
我想将 slug
作为我模型上的主键,而且由于我使用的是 MongoDB,我想使用 _id
而不是 id
.
I would like to make slug
my primary key on my model, and also since I'm working with MongoDB, I would like to use _id
instead of id
.
有没有人想出如何做到这一点?我的潜在问题是,当我在模型上执行多个 App.MyModel.find()
时,模型记录会被加载两次.
Has anyone figured out how to do this? My underlying problem is that model records get loaded twice when I do several App.MyModel.find()
on the model.
推荐答案
从 Ember Data 1.0 beta 开始,您可以在相应的序列化程序上定义 primaryKey
.
As of Ember Data 1.0 beta you define primaryKey
on the respective serializer.
对于整个应用
App.ApplicationSerializer = DS.RESTSerializer.extend({
primaryKey: '_id'
});
对于单一类型
App.FooSerializer = DS.RESTSerializer.extend({
primaryKey: '_id'
});
您仍将在模型上将其称为 id
,但 Ember Data 会在传输过程中将其序列化/反序列化为 _id
.
You will still refer to it as id
on the model, but Ember Data will serialize/deserialize it to _id
during transfer.
示例:http://emberjs.jsbin.com/OxIDiVU/635/edit
在此处阅读更多相关信息:http://emberjs.com/api/data/classes/DS.RESTSerializer.html#property_primaryKey
Read More about it here: http://emberjs.com/api/data/classes/DS.RESTSerializer.html#property_primaryKey
这篇关于对 Ember 数据使用主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!