Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 5 Laravel的最新更新_Laravel 5_Eloquent_Vuejs2 - Fatal编程技术网

Laravel 5 Laravel的最新更新

Laravel 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);

我的数据库中有一个图书列表,每本书都有章节。我的模特是

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 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)
进行查询。