2016-02-15 6 views
5

Sto cercando di recuperare un elenco di generi a cui è assegnata una traccia, sto usando una query eloquente whereHas ma mi sento un po 'persa.Larquel eloquente - Recupera i risultati solo se esiste la relazione

Ho il seguente

//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 

Sono consapevole che il mio caso è vuota, Attualmente il mio print_r restituisce il seguente:

         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** 

Una spinta nella giusta direzione sarebbe grande, io Sto trovando tutta questa roba eloquente davvero utile ma difficile da racimolare.

Grazie

risposta

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

In questo modo si otterrà genere solo se hanno tracce e desiderosi caricarli, se non volete eager loading rimuovere ::with('tracks')

+0

Credo formulato la mia domanda male, ho vinto' Ho campi null, mi piacerebbe solo visualizzare generi con una traccia ad essi correlata, la mia cattiva. – ExohJosh

+0

Ok la tabella delle tracce hanno 'genre_id'? – Froxz

+0

Sì, con la relazione di modello impostata in modo genere di funzione pubblico() { return $ this-> belongsTo (\ App \ Genre :: class, 'GenreId', 'id'); } – ExohJosh

Problemi correlati