Ember Data: Saving relationships

后端 未结 3 491
时光说笑
时光说笑 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 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);
        });
    

提交回复
热议问题