Whant to select genre book with selected book id first . one to many relation

Viewed 20

I have genres('id','title','top_book_id') and books('id','title') and book_genres('id','book_id','genre_id'). One book may contain in more than one genres . When I getting all books of genre I need first book to be book which is in 'top_book_id' of genre table .

So when I do $genre->books()->->paginate(12) for example I need first book to be 'top_book_id' of this genre . Is it possible ?

I tried this

  if($genre->top_book_id){
            $topBookIndex = $books->get()->filter(function($book) use ($genre) {
                return $book->book_id === $genre->top_book_id;
            });

            if($topBookIndex->count()) {
                $books->get()->forget(array_keys($topBookIndex->toArray())[0]);
            }
            $books->get()->push($top_book);
    }

But this didnt worked . Is it possible to get already with top_book_id first when I call $genre->books()?

1 Answers

Here is what you can try, I haven't.

// Get Top Book Eloquent Collection
$topBook = $books->where('id', $genre->top_book_id)->get();

// Get Other Books in Eloquent Collection
$books = $books->get();

// Merge them, make sure books are merged to topBook
$books = $topBook->merge($books)

Ref: https://laravel.com/docs/9.x/collections#method-merge

Related