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?