Reputation: 143
I have a list of books in my database and each book have chapters. my models are
Books.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
protected $guarded = [];
public function chapters()
{
return $this->hasMany(Chapter::class);
}
}
Chapter.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Chapter extends Model
{
protected $guarded = [];
public function book()
{
return $this->belongsTo(Book::class);
}
}
How can make a page that will show the books in order manner from latest to old? Also, the order is based on the chapter being updated or added in a book. If one of the old books is being updated by adding 1 more chapter, that book will show first on the most recent updated books. Thank you!
I am using Laravel 5.6 and Vue JS
Upvotes: 0
Views: 292
Reputation: 2683
Option 1:
You should use joins in query:
$books = Books::select('books.*')
->leftJoin('chapters', 'chapters.book_id', '=', 'books.id')
->groupBy('books.id')
->orderByDesc('chapters.updated_at')
->get();
Option 2:
If you don't need paginate and want to show all books in one page, you can try to sort a collection by relation value.
Add latestChapter relation:
public function latestChapter()
{
return $this->hasOne(Chapter::class)->orderByDesc('updated_at');
}
Get and sort:
$books = Books::with('latestChapter')->get();
$books = $books->sortByDesc(function($item){
return $item->latestChapter ? $item->latestChapter->updated_at : '1970-01-01';
});
Upvotes: 1