EmberJS - Relacionamentos

Ember.js fornece tipos de relacionamento para especificar como os modelos estão relacionados entre si. Existem diferentes tipos de relacionamento, como relacionamento Um para Um que pode ser usado com DS.belongsTo , relacionamento Um para Muitos pode ser usado com DS.hasMany junto com DS.belongsTo e relacionamento Muitos-para-Muitos podem ser usados ​​com DS.hasMany .

Sintaxe

import DS from 'ember-data';

export default DS.Model.extend ({
   var_name1: DS.belongsTo('model_name1'),
   var_name2: DS.hasMany('model_name2')
});

Exemplo

O exemplo fornecido abaixo mostra o uso de tipos de relacionamento. Crie dois adaptadores com os nomes conta e equipe usando o seguinte comando -

ember generate adapter adapter_name

Agora abra o arquivo app / adapters / account.js e adicione o seguinte código -

import ApplicationAdapter from './application';

//created an "account" array to store relationship data 
const account = {
   "data": {
      "type": "account",
      "id": "100",

      "relationships": {
         "secondVal": {
            "data": {
               "type": "staff",
               "id": "2"
            }
         },
         "firstVal": {
            "data": {
               "type": "staff",
               "id": "1"
            }
         }
      }
   }
};

export default ApplicationAdapter.extend ({
   //this method fetches data from 'staff' adapter
   findRecord() {
      //returns the data from array
      return account;
   }
});

Abra o arquivo app / adapters / staff.js e adicione o seguinte código -

import ApplicationAdapter from './application';
import Ember from 'ember';

//values given for type and id
const relval1 = {
   data: {
      type: "staff",
      id: "1",
      attributes: {
         name: 'JavaScript'
      }
   }
};

const relval2 = {
   data: {
      type: "staff",
      id: "2",
      attributes: {
         name: 'jQuery'
      }
   }
};

//the variable 'relval3' pushes the data to 'relval1' and 'relval2'
const relval3 = Ember.A();
relval3.pushObject(relval1);
relval3.pushObject(relval2);

export default ApplicationAdapter.extend ({
   findRecord(store, type, id) {
      //finds the item id and returns to 'relval3' variable
      let valret = relval3.find(function (item) {
         return id === Ember.get(item, 'data.id');
      });
      //the searched item will passed to 'relval3' from 'valret' variable
      return valret;
   }
});

Crie dois modelos com os nomes conta e equipe . Abra o arquivo app / models / account.js e inclua o seguinte código -

import DS from 'ember-data';
import Model from "ember-data/model";
import attr from "ember-data/attr";

//defines one-to-one and one-to-many relationship between models
import { belongsTo, hasMany } from "ember-data/relationships";

export default DS.Model.extend({
   //when async is 'true', it will fetch related entries
   firstVal: belongsTo('staff', {async: true}),
   secondVal: belongsTo('staff', {async: true})
});

Agora abra o arquivo app / models / staff.js e inclua o seguinte código -

import DS from 'ember-data';
import Model from "ember-data/model";
import attr from "ember-data/attr";
import { belongsTo, hasMany } from "ember-data/relationships";

export default DS.Model.extend ({
   //specifying attributes using 'attr()' method
   name: attr()
});

Em seguida, crie uma rota e nomeie-a como application.js . Abra este arquivo, que é criado em app / routes / e adicione o seguinte código -

import Ember from 'ember';

export default Ember.Route.extend ({
   model(){
      //returns the value of model() hook
      return this.get('store').findRecord('account', 100);  //retrieve a record for specific id        
   }
});

Crie um serializador com o nome do aplicativo usando o seguinte comando -

ember generate serializer serializer_name

Abra o arquivo app / serializers / application.js e adicione o seguinte código -

import DS from 'ember-data';

//it is the default serializer and works with JSON API backends
export default DS.JSONAPISerializer.extend ({
   
   //keyForRelationship() method overwrites the naming conventions
   keyForRelationship: function(key, relationship, method) {
      return Ember.String.camelize(key);  //returns the lowerCamelCase form of a string
   }
});

Abra o arquivo application.hbs criado em app / templates / com o seguinte código -

<h2>Model Relationships</h2>
//display the id along with the name
{{model.firstVal.id}} : {{model.firstVal.name}}
<br>
{{model.secondVal.id}} : {{model.secondVal.name}}
{{outlet}}

Resultado

Execute o servidor ember; você receberá a seguinte saída -