Reputation: 2238
I have a history of every rental of a book from the library and based on that I want to show current status of ALL BOOKS in the library. If I have only id, book_id, status (bool), and timestamps how should I do it in the easiest way without touching SQL? I want to have the freshest record for every book_id for example:
|--|-------|------|----------|
|id|book_id|status|timestamp-|
|--|-------|------|----------|
| 1| 1| 0|12.12.2019|
| 2| 2| 0|13.12.2019|
| 3| 3| 0|14.12.2019|
| 4| 2| 1|15.12.2019|
| 5| 3| 1|16.12.2019|
| 6| 3| 0|17.12.2019|
|--|-------|------|----------|
and I want to get this:
|--|-------|------|----------|
|id|book_id|status|timestamp-|
|--|-------|------|----------|
| 1| 1| 0|12.12.2019|
| 4| 2| 1|15.12.2019|
| 6| 3| 0|17.12.2019|
|--|-------|------|----------|
Ideas?
Upvotes: 0
Views: 181
Reputation: 142
$lastestBookRentHistory = YourBookRentHistoryModel::where('book_id', 123)->latest();
Note: latest()
works only if you have created_at
column on your table.
This is how latest()
is defined.
public function latest($column = 'created_at')
{
return $this->orderBy($column, 'desc');
}
If your timestamp column is not named as created_at
, use lastest('your-column-name') instead.
Upvotes: 2