Ember Data: Saving relationships

独自空忆成欢 提交于 2019-12-30 00:35:28

问题


I need to save a deep object to the server all at once and haven't been able to find any examples online that use the latest ember data (1.0.0-beta.4).

For example, with these models: (jsfiddle)

App.Child = DS.Model.extend({
    name: DS.attr('string'),
    age: DS.attr('number'),
    toys: DS.hasMany('toy', {async:true, embedded:'always'}),
});
App.Toy = DS.Model.extend({
    name: DS.attr('string'),
    child: DS.belongsTo('child')
});

And this code:

actions: {
    save: function(){
        var store = this.get('store'),
            child, toy;

        child = store.createRecord('child', {
            name: 'Herbert'
        });
        toy = store.createRecord('toy', {
            name: 'Kazoo'
        });

        child.set('toys', [toy]);
        child.save();
    }
}  

It only saves the JSON for the child object but not any of the toys -- not even side loaded:

{
  child: {
    age: null
    name: "Herbert"
  }
}

Do I have to manually save the toys too? Is there anyway that I can have it send the following JSON to the server:

{
  child: {
    age: null
    name: "Herbert",
    toys: [{
        name: "Kazoo"
    }]
  }
}

Or

{
  child: {
    age: null
    name: "Herbert",
    toys: [1]
  }
}

See JSFiddle: http://jsfiddle.net/jgillick/LNXyp/2/


回答1:


The answers here are out of date. Ember Data now supports embedded records, which allows you to do exactly what you're looking to do, which is to get and send the full object graph in one big payload. For example, if your models are set up like this:

App.Child = DS.Model.extend({
    name: DS.attr('string'),
    age: DS.attr('number'),
    toys: DS.hasMany('toy')
});
App.Toy = DS.Model.extend({
    name: DS.attr('string'),
    child: DS.belongsTo('child')
});

You can define a custom serializer for your Child model:

App.ChildSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    toys: {embedded: 'always'}
  }
});

This tells Ember Data that you'd like 'toys' to be included as part of the 'child' payload. Your HTTP GET response from your API should look like this:

{
  "child": {
    "id": 1,
    "name": "Todd Smith",
    "age": 5,
    "toys": [
      {"id": 1, "name": "boat"},
      {"id": 2, "name": "truck"}
    ]
  }
}

And when you save your model, Ember Data will send this to the server:

{  
   "child":{  
      "name":"Todd Smith",
      "age":5,
      "toys":[  
         {  
            "id":"1",
            "name":"boat",
            "child":"1"
         },
         {  
            "id":"2",
            "name":"truck",
            "child":"1"
         }
      ]
   }
}

Here is a JSBin that demonstrates this.

http://emberjs.jsbin.com/cufaxe/3/edit?html,js,output

In the JSbin, when you click the 'Save' button, you'll need to use the Dev Inspector to view the request that's sent to the server.




回答2:


toys can't be both async and embedded always, those are contradicting options. Embedded only exists on the active model serializer currently.

toys: DS.hasMany('toy', {embedded:'always'})

the toys are a ManyToOne relationship, and since the relationship exists on the belongsTo side it is more efficient to save the relationship during the toy's save. That being said, if you are creating it all at once, then want to save it in one big chunk that's where overriding comes into play.

serializeHasMany: function(record, json, relationship) {
  var key = relationship.key;

  var relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship);

  if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany' ||
      relationshipType === 'manyToOne') {
    json[key] = get(record, key).mapBy('id');
    // TODO support for polymorphic manyToNone and manyToMany relationships
  }
 },

And your save should be like this

    var store = this.get('store'),
        child, toy;

    child = store.createRecord('child', {
        name: 'Herbert'
    });
    toy = store.createRecord('toy', {
        name: 'Kazoo'
    });

    child.get('toys').pushObject(toy);
    child.save().then(function(){
       toy.save();
    },
    function(err){
      alert('error', err);
    });



回答3:


I needed a deep object, instead of a side-loaded one, so based on kingpin2k's answer, I came up with this:

DS.JSONSerializer.reopen({
    serializeHasMany: function(record, json, relationship) {
        var key = relationship.key,
            property = Ember.get(record, key),
            relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship);

        if (property && relationshipType === 'manyToNone' || relationshipType === 'manyToMany' ||
            relationshipType === 'manyToOne') {

            // Add each serialized nested object
            json[key] = [];
            property.forEach(function(item, index){
                json[key].push(item.serialize());
            });
        }
    }
});

Now when you call child.serialize(), it will return this object:

{
  child: {
    name: "Herbert",
    toys: [
      {
        name: 'Kazoo'
      }
    ]
  }
}

Which is what I need. Here's the jsfiddle with it in action: http://jsfiddle.net/jgillick/LNXyp/8/



来源:https://stackoverflow.com/questions/20714858/ember-data-saving-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!