简体   繁体   中英

Ember data, relationships and JSON

I have the following JSON being returned from an API:

{
"project": [
    {
        "id": "1",
        "name": "My First Project",
        "owned_by": "1",
        "updated_at": {
            "date": "2015-05-06 15:46:27.000000",
            "timezone_type": 3,
            "timezone": "Europe/London"
        },
        "created_at": {
            "date": "2015-05-06 15:46:27.000000",
            "timezone_type": 3,
            "timezone": "Europe/London"
        }
    }
],
"subscriptions": [
    {
        "id": "10",
        "output": "Hello World",
        "project_id": "1",
        "owned_by": "1",
        "updated_at": {
            "date": "2015-05-06 16:56:40.000000",
            "timezone_type": 3,
            "timezone": "Europe/London"
        },
        "created_at": {
            "date": "2015-05-06 16:56:40.000000",
            "timezone_type": 3,
            "timezone": "Europe/London"
        }
    }
]
}

And I have the following models:

project.js

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),
    ownedBy: DS.attr('string'),
    subscriptions: DS.hasMany('subscription')
});

subscription.js import DS from 'ember-data';

 export default DS.Model.extend({
     input: DS.attr('string'),
     projects: DS.belongsTo('project'),
 });

The data is being successfully returned from the API and I can get the project details, but I can't seem to get the data for the relationship. Using the ember inspector shows the data in the data tab but when I try and loop through this data with {{#each item in model.subscription}} nothing is returned.

在此处输入图片说明

your project json doesnt have any reference to its subscriptions. the project json should have an array of ids on it, each id relating to the subscription id.
Example code below from emberjs.com but substituting project for post and subscription for comment in your case

{
  "post": {
    "id": 1,
    "title": "Node is not omakase",
    "comments": [1, 2, 3]
  },

  "comments": [{
    "id": 1,
    "body": "But is it _lightweight_ omakase?"
  },
  {
    "id": 2,
    "body": "I for one welcome our new omakase overlords"
  },
  {
    "id": 3,
    "body": "Put me on the fast track to a delicious dinner"
  }]
}

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