Kristo
Kristo

Reputation: 557

Laravel 4 > eager loading > orderBy nested relationship

I´ve got 3 Models

1 - Gallery

class Gallery extends \Eloquent {

    public function media()
    {
        return $this->hasMany('Media');
    }

}

2- Media

class Media extends \Eloquent {

    protected $table = 'media';

    public function labels()
    {
        return $this->belongsTo('Label');
    }

}

3 - Label

class Label extends \Eloquent {

    public function media()
    {
        return $this->hasMany('Media');
    }

}

I´m trying to load a specific Gallery with all it´s Media. Media should be grouped by associated Labels and ordered by Labels name column.

This isn´t working:

$gallery = Gallery::with( [ 'media.labels' => function( $q )
{
    $q->orderBy( 'name', 'desc' );

} ] )->where( 'name', 'Gallery1' )->first();

To give an example how the output should be sorted:

Gallery1
    ALabel
        Media1
        Media2
    BLabel
        Media3
    CLabel
        Media4
        Media5
        Media6

Upvotes: 2

Views: 3065

Answers (3)

Harshan Morawaka
Harshan Morawaka

Reputation: 739

If you have more ordering with nested

$this->data['user_posts'] = User_posts::with(['likes', 'comments' => function($query) {
    $query->orderBy('created_at', 'DESC');
},
'comments.replies' => function ($query) { 
    $query->orderBy('created_at', 'DESC'); }
])->where('status', 1)->orderBy('created_at', 'DESC')->get();

Upvotes: 1

datOneperson
datOneperson

Reputation: 29

Looks like you need to join the labels to your gallery and do an order by to the main query.

https://stackoverflow.com/a/18882219/3681253

Upvotes: 0

damiani
damiani

Reputation: 7381

If you want to order just by the labels relation, this will work:

$gallery = Gallery::with(array(
            'labels' => function ($query) 
                { $query->orderBy('name', 'asc'); },
            'labels.media'
            ))->first();

If you want to have control over sorting for each level of the nested relationships (i.e. sort the labels by their name, and sort media by a column media_name), you can do this:

$gallery = Gallery::with(array(
            'labels' => function ($query) 
                { $query->orderBy('name', 'asc'); },
            'labels.media' => function ($query) 
                { $query->orderBy('media_name', 'asc'); }
            ))->first();

Upvotes: 6

Related Questions