I've been trying to figure out the proper way to get all the data from a record via a foreign key. I have simple app where users can add books to their "bookshelf".
Here are my tables:
USERS
ID | NAME |
BOOKS
ID | PAGES | NUMBER_OF_CHAPTERS
BOOKSHELF
ID | USER_ID (foreign key to `users.id`) |
BOOKSHELF_BOOKS
ID | BOOKSHELF_ID (foreign key to `bookshelf.id`) | BOOKS_ID (foreign key to `books.id`)
In my Eloquent Models, a bookshelf
hasMany books and bookshelf_books
belongsTo a bookshelf
and I have set those up in my models.
What happens is users create a "bookshelf" and add books to it from the list of books.
I'm at the point where I need to render the bookshelf with the user's books.
When I retrieve my bookshelf books with a call like Bookshelf::find($id)->books, the books that belong to that bookshelf return just fine..but only columns from the bookshelf table. So I get in return the bookshelf id, the user id, and the book id.
What I want to have returned is all the data of the book itself when i query for books in the bookshelf, not just it's id. E.G. [{"book_id":1, "pages":364, "number_of_chapters":14},{"book_id":2, "pages":211, "number_of_chapters":9}]
.
I've been scratching my head all day trying to figure out how to take this "join" one step further in Laravel/Eloquent ORM.
Would love any help with this, thanks!!
Get Current Week Data in Laravel Using the below Laravel eloquent query for fetching the current week data from the MySQL database table. $current_week = User::whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->get();
You only need to set local_key if you want to use a column other than what Laravel recognizes as your table's primary key. By default this is indeed id , but if you've already set the $primaryKey attribute to, say, foo_id , there's no need to specify foo_id as the local_key .
Just eager load the relationship
Change
Bookshelf::find($id)->books
to
Bookshelf::with('books')->find($id)->books
What about just doing it manually, and building your own array.
$bookshelf = Bookshelf::find($id)->books;
$thebooks = array();
foreach($bookshelf as $val){
$book = Book::find($val->book_id);
$thebooks[] = $book;
}
Then just return $thebooks
to the View. Which will be an array of book models.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With