Ember Data嵌入的belongsTo关系返回null

时间:2014-09-20 17:15:37

标签: ember.js ember-data

我有两种模式:

Question = DS.Model.extend

  answers: DS.hasMany("answer")

Answer = DS.Model.extend

  question: DS.belongsTo("question")

json提供问题中嵌入的答案:

"questions": [{
  "id":"1.04"
  "text":"What is the position or title of the 1% who is being protested against?",
  "answers":[
    {
      "text":"City mayor",
      "id":"1.04.02"
    },
    {
      "text":"City council member",
      "id":"1.04.03"
    },
    {
      "text":"CEO of some company",
      "id":"1.04.01"
    }
  ]
}]

当我拨打question.get('answers')时,Ember会返回预期的答案数组。但是,如果我调用answer.get('question'),则为null。知道为什么会这样吗?

2 个答案:

答案 0 :(得分:1)

我认为你需要告诉Ember你的关系将被嵌入,这样就完成了。

Question = DS.Model.extend

  answers: DS.hasMany("answer", embedded: 'always')

Answer = DS.Model.extend

  question: DS.belongsTo("question", embedded: 'always')

话虽如此,你可能想重新考虑一下你的json结构,嵌入式记录会引起很多人的共鸣。

Ember希望开箱即用。

{
  "questions": [
    {
      "id": "1.04"
      "text": "What is the position or title of the 1% who is being protested against?"
      "answer_ids": ["1.04.02", "1.04.03", "1.04.01"]
    }
  ],
  "answers": [
    {
      "text": "City mayor",
      "id": "1.04.02",
      "question_id": "1.04"
    },
    {
      "text": "City council member",
      "id": "1.04.03",
      "question_id": "1.04"
    },
    {
      "text": "CEO of some company",
      "id": "1.04.01",
      "question_id": "1.04"
    }
  ]
}

答案 1 :(得分:0)

假设你的question.get('answers')有效,你只需要升级到Ember Data beta.10,这就增加了对双方关系的支持。