mercredi 24 mai 2017

How to order a collection by a property of a child collection with a many to many relationship using Eloquent

I am using Laravel 5.4.

I have two models with a many to many relationship using an artist_album pivot table:

Album class:

class Album extends Model
{
    public function artists()
    {
        return $this->belongsToMany(Artist::class, 'artist_album');
    }
}

Artist class:

class Artist extends Model
{
    public function albums()
    {
        return $this->belongsToMany(Album::class, 'artist_album');
    }
}


I need to make a query using Eloquent to get a collection like this:

\Album {
    id: 9,
    name: "Octavarium (U.S. Version)",
    artists: {
        all: [
            \Artist {
                id: 2,
                name: "Dream Theater",
                pivot: Illuminate\Database\Eloquent\Relations\Pivot {
                   album_id: 9,
                   artist_id: 2,
                },
            }
        ],
    },
}

That should be ordered by the artist name.


I already tried with \Album::with('artists')->get()->sortBy('artists.name'); but it sorts the results using album.id instead of artists.name



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2qUHyhq
via IFTTT

Aucun commentaire:

Enregistrer un commentaire