Ember Data: Saving relationships

后端 未结 3 470
时光说笑
时光说笑 2020-12-28 20:11

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,

相关标签:
3条回答
  • 2020-12-28 20:50

    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/

    0 讨论(0)
  • 2020-12-28 20:57

    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.

    0 讨论(0)
  • 2020-12-28 21:04

    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);
        });
    
    0 讨论(0)
提交回复
热议问题