lundi 21 décembre 2015

Eager loading two tables with multiple Realtionships in laravel 5

i have 3 models Tracktype, Tracks and Subgenres . The relationship is like this . A Tracktype has many tracks and a track can have many subgenres . but a track can only have one track type

i have already defined relationships like these

/**
 * Gets the tracks lists Associated with a track type
 *
 * @return \Illuminate\Database\Eloquent\Relations\hasMany
 */
public function tracks()
{
    return $this->hasMany('App\Tracks', 'id', 'id');
}


/**
 * Get the Lists of tracks Associated with the Subgenre ID
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
 */
public function tracks()
{
    return $this->belongsToMany('App\Tracks', 'subgenre_track', 'subgenre_id', 'track_id');
}

i have tried something like this .

App\TrackType::with(['tracks.subgeneres' => function ($query) {
    $query->where('name', 'Trans');
}])->where('name', 'Single')->get();

But its not returning the correct results

Array ( [0] => Array ( [query] => select * from tracktype where name = ? [bindings] => Array ( [0] => Single )

        [time] => 0.55
    )

[1] => Array
    (
        [query] => select * from `tracks` where `tracks`.`id` in (?)
        [bindings] => Array
            (
                [0] => 1
            )

        [time] => 0.45
    )

)

My need is to get all tracks which are matching Tracktype of Single and Subgeneres matching Trans . i have both Tracktype table and Subgeneres table along with relevant pivot tables

i have read the docs many times and did some googling but no luck . if anyone can point out me to how to define these relationships and explain little bit, it will be help alot :)



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire