简体   繁体   中英

Ember.js hasMany/belongsTo custom foreign key

I would like to add an employee belongsTo a business and a business hasMany employees relationship but the foreign key is businessId instead of business_id . Where can I configure Ember to allow businessId to be the foreign key?

In fact how can I make modelId the format for all foreign keys?

we are using Ember data 1.13 , ember-cli 1.13

controllers/employee.js

import DS from 'ember-data';

export default DS.Model.extend({
  business: DS.belongsTo('business', { async: true })
});

controllers/business.js

import DS from 'ember-data';

export default DS.Model.extend({
  employees: DS.hasMany('employee', { async: true })
});

You can implement a custom serializer to transform the desired key in your JSON payload to match the property defined in your model:

  //in app/serializers/employees
  import Ember from 'ember';
  import DS from 'ember-data';

  export default DS.RESTSerializer.extend({
    normalizeHash: {
      employees: function(hash) {
        hash.business_id = hash.businessId;
        delete hash.businessId;
      return hash;
    }
  }
  });

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