Laravel 5 Laravel的最新更新
我的数据库中有一个图书列表,每本书都有章节。我的模特是 Books.phpLaravel 5 Laravel的最新更新,laravel-5,eloquent,vuejs2,Laravel 5,Eloquent,Vuejs2,我的数据库中有一个图书列表,每本书都有章节。我的模特是 Books.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Book extends Model { protected $guarded = []; public function chapters() { return $this->hasMany(Chapter::class);
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
protected $guarded = [];
public function chapters()
{
return $this->hasMany(Chapter::class);
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Chapter extends Model
{
protected $guarded = [];
public function book()
{
return $this->belongsTo(Book::class);
}
}
选项1:
您应该在查询中使用联接:
$books = Books::select('books.*')
->leftJoin('chapters', 'chapters.book_id', '=', 'books.id')
->groupBy('books.id')
->orderByDesc('chapters.updated_at')
->get();
选项2:
如果不需要分页,并且希望在一页中显示所有书籍,可以尝试按关系值对集合进行排序
添加最新章节关系:
public function latestChapter()
{
return $this->hasOne(Chapter::class)->orderByDesc('updated_at');
}
获取并排序:
$books = Books::with('latestChapter')->get();
$books = $books->sortByDesc(function($item){
return $item->latestChapter ? $item->latestChapter->updated_at : '1970-01-01';
});
有没有办法只在视图上显示5本最新更新的书籍?@Imperatura添加->limit(5)
进行查询。