2016-02-15 22 views
5

sonuçları al Onlara bir parça atanmış bir türler listesi almaya çalışıyorum, ben bir yereHangi bir sorgu kullanıyorum ama biraz kayıp hissediyorum.Eloquent Laravel - Yalnızca ilişki varsa

Ben ben benim boş, şu anda benim print_r aşağıdaki döndürür farkındayım aşağıdaki

//model 
public function workingGenre() { 
    $this->whereHas('tracks', function($query) { 
     $query->where(''); 
    }); 

    return $this->tracks()->first(); 
} 

//controller (where i am passing variables etc) 
$genres = Genre::with('tracks')->get(); 

//my view 
@foreach($genres as $genre) 
    {{print_r($genre->workingGenre())}} 
@endforeach 

:

         1 
             App\Track Object 
(
[table:protected] => Track 
[fillable:protected] => Array 
    (
     [0] => id 
     [1] => GenreId 
     [2] => Title 
     [3] => CreatedById 
     [4] => SelectedCount 
     [5] => ProducerName 
     [6] => SourceId 
     [7] => Published 
    ) 

[connection:protected] => 
[primaryKey:protected] => id 
[perPage:protected] => 15 
[incrementing] => 1 
[timestamps] => 1 
[attributes:protected] => Array 
    (
     [id] => 6 
     [GenreId] => 4 
     [Title] => Guns Up 
     [CreatedById] => 1 
     [SelectedCount] => 0 
     [ProducerName] => 
     [SourceId] => 1 
     [Published] => 1 
    ) 

[original:protected] => Array 
    (
     [id] => 6 
     [GenreId] => 4 
     [Title] => Guns Up 
     [CreatedById] => 1 
     [SelectedCount] => 0 
     [ProducerName] => 
     [SourceId] => 1 
     [Published] => 1 
    ) 

[relations:protected] => Array 
    (
    ) 

[hidden:protected] => Array 
    (
    ) 

[visible:protected] => Array 
    (
    ) 

[appends:protected] => Array 
    (
    ) 

[guarded:protected] => Array 
    (
     [0] => * 
    ) 

[dates:protected] => Array 
    (
    ) 

[dateFormat:protected] => 
[casts:protected] => Array 
    (
    ) 

[touches:protected] => Array 
    (
    ) 

[observables:protected] => Array 
    (
    ) 

[with:protected] => Array 
    (
    ) 

[morphClass:protected] => 
[exists] => 1 
[wasRecentlyCreated] => 
) 

**And so on** 

doğru yönde bir itme iyi olurdu, ben tüm bu elverişli şeyleri gerçekten kullanışlı buluyorum ama kafamı saracak kadar zor.

Teşekkür

cevap

6
$genres = Genre::with('tracks')->has('tracks')->get(); 
    foreach($genres as $genre) 
     //do what you need 
    endforeach 

onlar Tracks var ve istekli istediğiniz yoksa hevesli yükleme Ben kötü sorumu phrased düşünüyorum ::with('tracks')

+0

kaldırmak, onları yükleyin yalnızca Tür alacak Bu şekilde, ben 'kazandı Boş alanlara sahip olmak istiyorum, sadece onlarla ilgili bir izi olan türleri görüntülemek istiyorum, benim kötü. – ExohJosh

+0

Parçalarınızın tablosunda 'genre_id' var mı? – Froxz

+0

Yep, model ilişkisi ayarlandığında genel işlev türü() { $ this-> aittirTo (\ App \ Genre :: class, 'GenreId', 'id'); } – ExohJosh