Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 })
});
like image 300
monty_lennie Avatar asked Dec 14 '25 07:12

monty_lennie


1 Answers

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;
    }
  }
  });
like image 122
Christopher Milne Avatar answered Dec 16 '25 21:12

Christopher Milne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!