2

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
Kristo
  • 547
  • 1
  • 7
  • 20
  • I don't think it's correct that your `Media` `belongsTo('Label')`. This means each `Media` has only one `Label`. Rather you should use `belongsToMany('Label')`, since each `Media` may have multiple `Label`s. – Andy Feb 10 '15 at 19:34
  • Thanks for pointing this out. My output Example was a little bit confusing but it´s exactly what I want: Each Media belongs to one Label at once - not multiple. I optimised the output Example – Kristo Feb 11 '15 at 22:12

3 Answers3

6

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();
damiani
  • 7,071
  • 2
  • 23
  • 24
  • What if labels are not related to galleries? As you can see in my models media belongs to label and gallery has many media - is there a way to achieve the given output example without relating labels with galleries? – Kristo Nov 02 '14 at 00:45
1

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();
0

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

Community
  • 1
  • 1