简体   繁体   English

有没有一种方法可以使用相关模型的ID创建一个带有belongsTo关联的余烬数据模型?

[英]Is there a way to create an ember-data model with a belongsTo association using the associated model's id?

I have the id of a model I know should exist, and I would like to create a record with a belongsTo association to this model. 我有一个我知道应该存在的模型的ID,并且我想创建一个与这个模型的belongsTo关联的记录。 However, I would like to only provide the id when creating the association, rather than first query for the associated model. 但是,我只想在创建关联时提供ID,而不要首先查询关联模型。 Is this possible? 这可能吗?

This is what I would like to work (or some variant of it): 这是我想工作的(或其一些变体):

store.createRecord('person', {childId: '1', name: 'billybob'});

This is for a model defined as follows: 这是针对定义如下的模型的:

Person = DS.Model.extend({
  name: DS.attr('string'),
  child: DS.belongsTo('child'),
});

The guides suggest something like this: 指南建议如下:

store.createRecord('person', {child: child, name: 'billybob'});

Where child has already been fetched from the store at some point or is a newly created record. 某个时候已经从商店中获取了child ,或者是新创建的记录。

I was hoping to then return the child side-loaded. 我希望然后让孩子背负重担。 This could avoid needing endpoints on the backend to deal directly with children, as they are always handled via the person endpoints. 这可以避免需要后端上的端点直接处理孩子,因为它们始终通过人员端点进行处理。

Since we're only giving the backend the ID, it would need to fail if that record doesn't actually exist. 由于我们只为后端提供ID,因此如果该记录实际上不存在,它将需要失败。

I've tried various permutations such as: 我尝试了各种排列,例如:

store.createRecord('person', {child: {id: '1'}, name: 'billybob'});

and have attempted to customize the model's serializer without success. 并尝试自定义模型的序列化器,但未成功。

Any help is greatly appreciated. 任何帮助是极大的赞赏。

I think the best way for you to go is to create the record with store.push() first. 我认为最好的方法是首先使用store.push()创建记录。 Then you either can use store.unload to remove the store from the record, or make sure that adapter.shouldReloadRecord returns true for this record so it will get loaded the next time you find it. 然后,您可以使用store.unload从记录中删除商店,或者确保该记录的adapter.shouldReloadRecord返回true ,以便下次find该记录时将其加载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM