Eloquent Laravel - Get results only if there is a relationship

I'm trying to get a list of genres that have a track assigned to them, I use the whereHas eloquent request, but feel a little lost.

I have the following

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

I know that my Where is empty, currently my print_r returns the following:

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

Pushing in the right direction would be great, I find this all eloquent material very useful, but it's hard to wrap my head.

thanks

+5
source share
1 answer
 $genres = Genre::with('tracks')->has('tracks')->get(); foreach($genres as $genre) //do what you need endforeach 

Thus, you will only get Genre if they have tracks and Eager. Download them if you do not want to download the download. Remove ::with('tracks')

+6
source

Source: https://habr.com/ru/post/1243057/


All Articles