adopted-ember-addons / ember-data-model-fragments

Ember Data addon to support nested JSON documents
MIT License
369 stars 114 forks source link

access 'parent' model #313

Open ngouy opened 6 years ago

ngouy commented 6 years ago

let's have (like in the readMe)

// app/models/person.js
import Model from 'ember-data/model';
import {
  fragment,
  fragmentArray,
  array
} from 'ember-data-model-fragments/attributes';

export default Model.extend({
  name      : fragment('name'),
  addresses : fragmentArray('address'),
  // titles    : array()
});
// app/models/address.js
import attr from 'ember-data/attr';
import Fragment from 'ember-data-model-fragments/fragment';

export default Fragment.extend({
  street  : attr('string'),
  city    : attr('string'),
  region  : attr('string'),
  country : attr('string')
});

Is there any way, from an address instance, to retrieve the person 'parent' without adding an attribute in the address model and passing it as a params when creating a new one :


import Address from 'models/address'
import DS from 'ember-data'

Address.reopen({
    person: attr() // or belongsTo ?? whatever
});

let person = store.getById('person', '1');
let addresses = person.get('addresses');

addresses.createFragment({
  street  : '1 Shy Maid',
  city    : 'Rhoyne River',
  region  : 'Free Cities',
  country : 'Essos',
  person: person // but  theoretically we already know that because it's created from a person instance ... 
});

// then I can laster on access my parent with
random_adress.person

edit : while checking the code, I know that we can access it through this._internalModel._owner but as "private keys", we can't use it as a computed property like this._internalModel._ower.my_pp. So it doesn't solved my issue

allthesignals commented 5 years ago

I hear this but it sounds like this should be a regular ember-data relationship, on? I'm using fragments in my case to leverage computed properties...

lolmaus commented 5 years ago

Regular Ember Data relationships are not supported by Ember Data Model Fragments.

Is there a better solution?

jakesjews commented 5 years ago

It needs documentation but you can use import { fragmentOwner } from 'ember-data-model-fragments/attributes' for a macro that will allow access to the owner of the fragment