Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

TheAthenA714's avatar

Am I using hasManyThrough incorrectly?

Hello everyone!

I'm having a bit of a problem with some relationship in a new website I'm working on. I thought hasManyThrough was the answer, but I can't get it to work as I'd like. So either I'm using it incorrectly, or I should use something else, but I can't figure out what.

Let's consider three tables: Library, Book, Version.

Each Version of a Book is unique. So a Version belongs to only one book, but a Book has multiple versions. So this is a simple hasMany/belongsTo relationship. A Library sells different versions of different books, but a specific version can only belongs to one library. So this is another hasMany/belongsTo relationship between the Library and Version table.

So I have in my Version table two "library_id" and "book_id" fields for those relationship. I also defined the methods "library()" and "book()" in Version.php, as well as "versions()" in both Library.php and Book.php.

What I'd like to do, is get a list of books sold by a specific library. I could use a simple many-to-many relationship between library and book, but that implies a new table, and a bunch of code that I don't need. Since to get the list of books sold by a library, I simply need to fetch the list of versions sold in a library, and get the books associated with each version. I can do this using the query builder with this query:

  DB::table('versions')
  ->join('libraries', 'versions.library_id', '=', 'libraries.id')
  ->join('books', 'versions.book_id', '=', 'book.id')
  ->select('books.*')
  ->get();

This works perfectly, except it returns an array. I would like to find a way to do this while getting a Collection of Book. I tried using hasManyThrough but I can't get the correct results.

So, how am I supposed to do this? Do I have to create a many-to-many relationship? And BTW, how is this kind of relationship called?

0 likes
2 replies
pmall's avatar

In fact your version table works like a povit table of a many to many relationship. You can do :

class Library extends Eloquent {

    public function books () {

        return $this->belongsToMany(App\Book::class, 'versions');

    }

}

Here you just specify versions is the pivot table of the many to many relationship

Please or to participate in this conversation.