2014-06-12 31 views
5

Laravel'de 2 ilişkiyi birleştirmenin bir yolu var mı?Laravel birleştirme sadakatleri

Bu, şu anda kurulum yoludur, ancak her ikisi de birleştirilmiş olarak dönebilmemin bir yolu var mı?

public function CompetitionsHome() { 
    return $this->HasMany('Competition', 'home_team_id'); 
    } 
    public function CompetitionsGuest() { 
    return $this->HasMany('Competition', 'guest_team_id'); 
    } 
    public function Competitions() { 
    // return both CompetitionsHome & CompetitionsGuest 
    } 

cevap

15

İlişkilerden döndürülen birleştirilmiş koleksiyonları döndüren özellik için getter yöntemini deneyin.

public function getCompetitionsAttribute($value) 
{ 
    // There two calls return collections 
    // as defined in relations. 
    $competitionsHome = $this->competitionsHome; 
    $competitionsGuest = $this->competitionsGuest; 

    // Merge collections and return single collection. 
    return $competitionsHome->merge($competitionsGuest); 
} 

Ya da farklı sonuç kümeleri almak için koleksiyonun döndürülmesinden önce ek yöntemleri arayabilirsiniz. durumda

public function getCompetitionsAttribute($value) 
{ 
    // There two calls return collections 
    // as defined in relations. 
    // `latest()` method is shorthand for `orderBy('created_at', 'desc')` 
    // method call. 
    $competitionsHome = $this->competitionsHome()->latest()->get(); 
    $competitionsGuest = $this->competitionsGuest()->latest()->get(); 

    // Merge collections and return single collection. 
    return $competitionsHome->merge($competitionsGuest); 
} 
+0

Vay, bilmiyordum güzel Bu var! thx – Kiwi

+0

Mevcut Koleksiyon yöntemleri hakkında daha fazla bilgiyi buradan edinebilirsiniz http://laravel.com/api/class-Illuminate.Support.Collection.html#methods – Andreyco

+0

Yanıtı iyileştirin. – Andreyco

3

Eğer bir ilişki elde edilen bazı verilerinizin kaybedeceksiniz böylece, aynı indeks tuşlarıyla unsurları geçersiz kılacak iki koleksiyonları (ilişkileri) birleştirmek için birleştirme() yöntemini tercih etmektedir.

diğer koleksiyon İşte

sonuna bir koleksiyona iterek yeni dizi anahtarlarını oluşturur push() yerine yöntemini seçmelidir bir örnek:

public function getCompetitionsAttribute($value) { 
    $competitionsHome = $this->competitionsHome; 
    $competitionsGuest = $this->competitionsGuest; 

    // PUSH ONE TO OTHER! 
    return $competitionsHome->push($competitionsGuest); 
} 
+0

Bu, birincil/dizin anahtarlarının geçersiz kılınmasını önlemek için doğru bir yanıttır. –