简体   繁体   中英

How to use belongsTo in Ember

I have these models:

Gmcontrolpanel.Offer = DS.Model.extend({
  idShop: DS.attr('number'),
  name: DS.attr('string'),
  duration: DS.attr('string'),
  optionDuration: DS.attr('number'),

  products: DS.hasMany('product', {embedded: 'always'})
});

Gmcontrolpanel.Product = DS.Model.extend({
  name: DS.attr('string'),
  description: DS.attr('string'),

  offer: DS.belongsTo('offer')
});

Now I've understood how hasMany works; but for the belongsTo? How it is supposed to be the server answer for a product to let Ember-data know how to get the parent offer?

This will depend on your request.

In your Offer request, you'll want to include a list of ids for products that it's related to and you'll want to do the opposite for Products , like this:

{
   "offers": [
         {
             'id':1,
             'idShip':1,
             'name':'Offer 1',
             'duration':'3:00',
             'products':[1,2,3,4,5]
         }
   ]
}

{
       "products": [
             {
                 'id':1,
                 'name':'Product 1',
                 'offer':1
             }
       ]
    }

You can remove the {embedded: 'always'} from the hasMany . Ember will automatically kick off a request for each of the ids include. Alternatively, you can sideload the products or offers in the request by include all of them in one request, like this;

{
   "offers": [
         {
             'id':1,
             'idShip':1,
             'name':'Offer 1',
             'duration':'3:00',
             'products':[1,2,3,4,5]
         }
   ],
   "products": [
        {
             'id':1,
             'name':'Product 1',
             'offer':1
        }
   ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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