2013-10-01 68 views
0

我有兩個型號Retriving模型的hasMany關係

時間輸入

TimeTray.TimeEntry = DS.Model.extend({ 
    startTime: DS.attr('date'), 
    endTime: DS.attr('date'), 
    status: DS.attr('string'), 
    offset: DS.attr('number'), 
    isDeleted: DS.attr('boolean'), 
    task: DS.belongsTo('task'), 
    duration: function() { 
     return TimeTray.timeController.duration(this.get('startTime'), this.get('endTime')); 
    }.property('startTime', 'endTime'), 
    title: function() { 
     if (this.get('task')) { 
      return this.get('task').get('title'); 
     } 
    }.property('task') 
}); 

任務

TimeTray.Task = DS.Model.extend({ 
    title: DS.attr('string'), 
    totalTime: function() { 
     var timeEntries = this.get('timeEntries') 
     for (var entry in timeEntries) { 
      var duration = entry.get('duration') 
     } 
    }.property('timeEntries'), 
    isDeleted: DS.attr('boolean'), 
    isRecording: DS.attr('boolean', { defaultValue: false }), 
    timeEntries: DS.hasMany('TimeEntry') 
}); 

我如何得到timeentry實體的陣列,這樣我可以計算花在一個任務上的總時間?上述方法不起作用。

時間條目標題屬性起作用。

+0

我可以知道爲什麼我的答案是取消接受? –

+0

嗨,我的問題不是javascript的語言的動態我知道什麼(......在..),事實證明,我假設如果我創建了關於timeEntry關係的任務,燼將自動添加timeEntry任務。但它沒有,所以我不得不返回一個數組與timeEntry ID的任務。如果你把這個添加到你的答案,我會很樂意重新接受它 – Billybonks

+0

好的。我錯過了這一點。現在答案已更新。 –

回答

1

你在你的代碼中的一些錯誤:

1-在這的foreach

... 
for (var entry in timeEntries) { 
    var duration = entry.get('duration') 
} 
... 

for ... in像你預期陣列無法正常工作,你需要使用或for(var i; i < array.length; i++)array.forEach(func)

2 - 在計算財產totalTime您將使用TimeEntryduration屬性,你需要指定使用property('[email protected]')這種依賴性。

3 - Probally您timeEntries財產將被抓取來自服務器的,所以你需要使用async: true選項,在你的定義:

timeEntries: DS.hasMany('TimeEntry', { async: true }) 

4 - 如果你的timeEntries總是空空的,連數據被保存在你的數據庫中。確保你的返回的json有timeEntries標識符。例如:

{id: 1, title: 'Task 1', timeEntries: [1,2,3] }  

更改後的代碼如下:

TimeTray.Task = DS.Model.extend({ 
    title: DS.attr('string'), 
    totalTime: function() { 
     var duration = 0; 
     this.get('timeEntries').forEach(function(entry) { 
      duration += entry.get('duration') 
     }); 
     return duration; 
    }.property('[email protected]'), 
    isDeleted: DS.attr('boolean'), 
    isRecording: DS.attr('boolean', { defaultValue: false }), 
    timeEntries: DS.hasMany('TimeEntry', { async: true }) 
}); 

而這是與該樣品的工作http://jsfiddle.net/marciojunior/9DucM/

我希望它能幫助

0

totalTime方法是小提琴既不總結timeEntry持續時間也不返回值。您的property設置不正確(使用@each)。這樣做的正確的方法是:

totalTime: function() { 
    var timeEntries = this.get('timeEntries') 
    var duration = 0; 
    for (var entry in timeEntries) { 
     duration = duration + entry.get('duration'); 
    } 
    return duration; 
}.property('[email protected]'), 

或者,更優雅的使用getEach()reduce()

totalTime: function() { 
    return this.get('timeEntries').getEach('duration').reduce(function(accum, item) { 
     return accum + item; 
    }, 0); 
}.property('[email protected]'),