Eric
Eric

Reputation: 1020

How to create multiple relationships between 2 models?

Using: Ember 2.5.1, Ember Data 2.5.2 with the JSONAPIAdapter

I am creating an application to track inter-store stock transfers.

I have a table called transfers:

+----+---------------+-------------+----------------+
| id | from_store_id | to_store_id | transfer_notes |
+----+---------------+-------------+----------------+
| 1  | 12            | 32          | transfer to 32 |
| 2  | 9             | 13          | transfer to 13 |
| 3  | 32            | 9           | transfer to 9  |
+----+---------------+-------------+----------------+

Each row represents a transfer and it's origin and destination stores.

I also have a table called stores:

+-----+----------+-------------+------------+
| id  | store_no | store_state | store_city |
+-----+----------+-------------+------------+
| 12  | tx12     | TX          | Dallas     |
| 9   | me09     | ME          | Bangor     |
| 32  | wa32     | WA          | Yakima     |
| 13  | tn13     | TN          | Memphis    |
+-----+----------+-------------+------------+

It seems to me that the relationships between these two tables are:

  1. A transfer belongs to a (origin) store
  2. A transfer also belongs to a (destination) store
  3. A store can have many transfers as both origin and destination store.

How can I define these relationships in Ember Data?

I recently picked Ember back up after a 3 year break and I am pretty confused as to how to define these relationships or if they are even correct. One of the things that is really throwing me off is the custom names of the from_store_id and to_store_id in the transfers table.

Any insights welcome.

If it matters I am using Sinatra with JSONAPI::Serializers

Upvotes: 0

Views: 223

Answers (1)

Henry Vonfire
Henry Vonfire

Reputation: 1281

You can define different relationships inside one model, even with itself. There is more information in the guides

In this case, you would do something like this:

//model storehouse.js
export default Model.extend({
  transferOrigins:hasMany('transfer', { inverse: 'storeOrigin' }),
  transferDestinations:hasMany('transfer', { inverse: 'storeDestination' }),
  storeNo:attr('string'),
  storeState:attr('string'),
  storeCity:attr('string')
});

//model transfer.js
export default Model.extend({
  storeOrigin:belongsTo('storehouse'),
  storeDestination:belongsTo('storehouse'),
  fromStoreId:attr('string'),
  toStoreId:attr('string'),
  transferNotes:attr('string')
});

Since you have multiple relationships with the same model, you help ember-data to understand which property is related with using inverse.

Here you have a full example in this ember-twiddle

Upvotes: 3

Related Questions