I have a table books and books has many images. So 2 tables are
- books
- book_images
In Book model I have written below function for hasMany relation with book_images
public function bookImages()
{
return $this->hasMany(BookImage::class);
}
In book model I have written another mathod call getBooks
public function getBooks(int $id = null, array $queryString = [])
{
$query = $this::where(['books.is_deleted' => false]);
$query = $query->with("bookImages","author","category")
->withCount(['favourites'])
;
return $query;
}
This getBooks method I have called from controller like below
return view('pages.top_page',[
'books' => (new Book)->getBooks()->orderBy('created_at','DESC')->get()->take(5),
]);
In debugger it looks an in query is running for all books example in database table there has 400 books but logically there should only 5. Is it debugger problem ? Or problem in my query ?
CodePudding user response:
In Laravel, the take
method is used to limit the number of results returned by a query. It is often used in combination with the get
method to retrieve a specific number of results from the database.
Since each Eloquent model serves as a query builder, you may add additional constraints to queries and then (after constraints) invoke the get()
method to retrieve the results (to avoid this situation):
(new Book)->getBooks()->orderBy('created_at','DESC')->take(5)->get()
This will retrieve the first 5 record from the database.
You can also use the take method in combination with the skip method to paginate the results of a query. For example:
$page = 1;
$perPage = 10;
//...
(new Book)->getBooks()->orderBy('created_at','DESC')
->skip(($page - 1) * $perPage)->take($perPage)->get()
This will retrieve the first 5 records on the first page, the next 5 records on the second page, and so on.
Keep in mind that the take
method will only work if you are using a database that supports limit and offset clauses, such as MySQL or PostgreSQL. If you are using a database that does not support these clauses, you can use the chunk
method instead.