2015-02-04 69 views
0

訪問雄辯的關係,說我有清單與一個屬性模型一個一對多的關係模型:如何使用關聯數組鍵

class Listing extends Eloquent { 
    public function attrs() { 
     return $this->hasMany('Attribute'); 
    } 
} 

class Attribute extends Eloquent { 
    public function listing() { 
     return $this->belongsTo('Listing'); 
    } 
} 

屬性有一個代碼和值。當我處理清單時,我希望能夠使用屬性代碼獲取特定屬性,如下所示:

$val = Listing::find($id)->attrs[$code]->value; 

上述行顯然不起作用。有很多方法可以解決這個問題(例如,維護一個由代碼索引的屬性的內部關聯數組,並將其填充到attrs()方法中;提供一個getter函數,並且只是通過attrs數組進行強力搜索),但是我想知道有一種使用Laravel內置的東西的優雅方式。

任何想法比我上面建議的更好?

回答

1

您可以使用first()法在Laravel集合封閉:

$val = Listing::find($id)->attrs->first(function($model) use ($code){ 
    return $model->code == $code; 
})->value; 

但是要知道,first()返回null如果沒有模型比賽,你會得到一個異常(因爲你不能訪問->value非對象

爲了避免包裝在的)的,如果:

$attribute = Listing::find($id)->attrs->first(function($model) use ($code){ 
    return $model->code == $code; 
}); 
$val = $attribute ? $attribute->value : 'default'; 

另外,您可以過濾的關係,我認爲這是更優雅:

$attribute = Listing::find($id)->attrs()->where('code', $code)->first(); 
$val = $attribute ? $attribute->value : 'default'; 
+0

好,並且有一個類似的解決方案,其中ATTRS關係是渴望裝的?我應該提到,在我原來的問題... – ralbatross

+0

如果他們急於加載,使用'first()'與過濾關閉 – lukasgeiter

+0

右。但是,如果我沒有弄錯,那基本上等同於我在模型上使用自定義getter的第二種解決方案,通過attrs數組進行強力搜索。但是你確實以Laravel-y的方式回答了這個問題,謝謝。 – ralbatross