Help sorting with a BelongsToMany relationship - on name field instead of id
I have a 'books' table and an 'authors' table. There can be multiple authors for a given book so I also have a table called 'authors_to_books' which has fields 'book_id' and 'author_id'.
In user's collections, I'd like to allow sorting by author name but I'm getting a little lost because of the pivot table (I think that's the correct term?). I can find similar questions with answers that lead to being able to sort by the pivot table / BelongsToMany relationship but they seem to be by the author_id on the authors_to_books table, not the author's name - which is on the 'authors' table.
I have these relationships on the 'books' model:
public function authorsToBook(): HasMany
{
return $this->hasMany(AuthorsToBook::class);
}
public function authors(): BelongsToMany
{
return $this->belongsToMany(Author::class, ‘authors_to_books’);
}
@Snapey Ah, I can see now how I was unclear in my original post. Yes, what I'm looking to do is sort Books by Author name...which, as you pointed out, becomes difficult because in some cases there are multiple authors per book.
Is there a way to just use the first author (or really any single author) for a book for purposes of sorting?