2015-07-20 91 views
1

我使用灰燼1.13.2和灰燼數據1.13.4獲取灰燼數據模型的關係型

我試圖尋找出類型的關係的一個模型。以下面的示例模型。

// my post model 
export default DS.Model.extend({ 
    author: DS.belongsTo('author'), 
    comments: DS.hasMany('comment') 
}); 

我怎麼能查一下我的代碼,如果comments是的hasMany或屬於關聯關係?

目前我已經制定出兩種可行的解決方案,但他們對我感覺有點混亂,我相信肯定有更好的方法。該工程

一種方式是這樣的

var relationship = post.get(relationshipName); // relationshipName = 'comments' 

if (relationship.constructor.toString().indexOf('Array') !== -1) { 
    relationshipType = 'hasMany'; 
} 
else if (relationship.constructor.toString().indexOf('Object') !== -1) { 
    relationshipType = 'belongsTo'; 
} 

的作品

var relationship = post.get(relationshipName); // relationshipName = 'comments' 

if (relationship.get('@each')) { 
    relationshipType = 'hasMany'; 
} 
else { 
    relationshipType = 'belongsTo'; 
} 

他們都工作的另一種方式,但他們都覺得有點笨重給我,我不知道如何可靠的他們是。

所以問題是,哪種方法更可靠?或者有更好的方法嗎?

+0

當訪問與'post.get('comments')'的關係時,您被賦予了值 - 不是特殊的關係對象。根據你的代碼,我建議將代碼移動到後期模型本身,如:'post.doSomethingWithAllBelongsTo()'並將該方法添加到你的後期模型中。在那裏你可以通過'this.eachRelationship'訪問那個模型的所有關係,你可以在那裏訪問這個類。 – enspandi

回答

1

你可以檢查fields

import Post from '../models/post' 

Ember.get(Post, 'fields').get('comments'); // hasMany 

或者,如果你有一個模型的實例,你可以勾選構造:

Ember.get(post.constructor, 'fields').get('comments'); // hasMany 
+0

謝謝,這正是我要找的 –

0

作爲的hasMany返回DS.ManyArray的實例,並屬於關聯返回DS.Model您可以通過instanceof檢查:

var something = post.get(relationshipName); // relationshipName = 'comments' 
var relationshipType = 'belongsTo'; 
if(something instanceof DS.ManyArray) { 
    relationshipType = 'hasMany'; 
} 

的進一步深入,你可以使用下面的代碼,以確定現場是不是在所有(即計算性能)的模型:

var something = post.get(name); 
var propertyType = 'unknown'; 
if(something instanceof DS.ManyArray) { 
    propertyType = 'relationship:hasMany'; 
} else if(something instanceof DS.Model) { 
    propertyType= 'relationship:belongsTo'; 
} else if(/*whatever you want*/) { 
    propertyType = /*whatever you want*/; 
} else { 
    propertyType = 'unknown'; 
} 

另一種方式,如果你不希望導入DS因任何原因是檢查「關係」屬性:

var something = post.get(relationshipName); // relationshipName = 'comments' 
var relationshipType = relationship.hasOwnProperty('relationship') ? 'hasMany' : 'belongsTo'; 

這一個是OK只有當你確定「的東西「是的關係,因爲它會給你假陽性,如果‘東西’只是一個模型,計算性能等

2

我認爲你正在尋找Model.eachRelationship 例如:

model.eachRelationship(function(name, descriptor) { 
    if (descriptor.kind === 'hasMany') { 
     //do something here 
    } 
}); 
+0

謝謝!很酷的答案 – DenQ