将 DB:table 查询转换为 eloquent

convert DB:table query to eloquent

我的控制器中有一个方法,其中我 return 来自数据库的书籍数组,如下所示:

$books= DB::table('books')->where('category_id', $category_id)->orderBy('title', 'asc')->paginate(20);

现在我希望能够使用 eloquent 关系与我认为这样的结果书数组:

@foreach($books as $book)
    <p>Title: {!! $book->title !!}
    <p>Category: {!! $book->category() !!}
@endforeach

根据我的理解,这是行不通的,因为 $books 数组不在 Eloquent 中。我怎样才能做到这一点?

我假设您已经有了 Bookcategory 模型并且两者之间存在关系

试试这个:

$books= Book::with('category')->orderBy('title', 'asc')->paginate(20);