Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent Laravel - Retrieve results only if the relationship exists

I am trying to retrieve a list of genres which have a track assigned to them, I am using a whereHas eloquent query 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'm aware 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**

A push in the right direction would be great, I am finding this whole eloquent stuff really useful but hard to wrap my head around.

Thanks

like image 846
ExohJosh Avatar asked Feb 15 '16 13:02

ExohJosh


1 Answers

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

This way you will get Genre only if they Have Tracks and Eager Load them, if you dont want eager loading remove ::with('tracks')

like image 99
Froxz Avatar answered Nov 10 '22 02:11

Froxz