How to pass identifiers for hasMany relationships using store.createRecord ()?

Suppose I have the following models:

// customer.js
DS.Model.extend({
  products: DS.hasMany('product')
});

// product.js
DS.Model.extend({
 customer: DS.belongsTo('customer')  
});

And I need to create a client with a list of products by identifiers ( which are not yet loaded from the backend ), something like this:

this.get('store').createRecord('customer', {products: [1, 2, 3]});  

But this fails, as the store expects the products to be an array of DS.Model:

Error processing route: index Approval error: all elements of the hasMany relation must be DS.Model instances, you passed [1,2,3]

How to create a record with your associations provided by identifiers?

+6
source share
2 answers

: : hasMany DS.Model, [1,2,3]

, DS.Model, createRecord, - ,

    let product1 = this.store.createRecord('product',{customer:1});
    let product2 = this.store.createRecord('product',{customer:2});    
    return this.get('store').createRecord('customer', {products:[product1,product2]});
+1

, , . - :

let customer = this.store.createRecord('customer', {});
customer.get('products').then(function() {
    customer.get('products').addObject(this.store.createRecord('product', {/* ... */}));
});
+1

Source: https://habr.com/ru/post/1015950/


All Articles