我正在使用Laravel框架进行项目开发,并使用DB外观运行原始的SQL查询。我使用了DB::select方法,但是在使用该DB原始查询时,分页方法不起作用并显示以下错误
Call to a member function paginate() on array
我想知道如何使用DB原始查询实现Laravel分页功能,这是我的代码:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Notice;
use Illuminate\Support\Facades\DB;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;
class NoticeController extends Controller
{
public function index(){
$notices = DB::select('select
notices.id,notices.title,notices.body,notices.created_at,notices.updated_at,
users.name,departments.department_name
FROM notices
INNER JOIN users ON notices.user_id = users.id
INNER JOIN departments on users.dpt_id = departments.id
ORDER BY users.id DESC')->paginate(20);
$result = new Paginator($notices,2,1,[]);
return view('welcome')->with('allNotices', $notices);
}
}
->paginate(20)
,为什么还要再使用new Paginator
?对于任何阅读此内容的人,请始终尝试理解您正在编写的内容,字面上阅读您所写的内容,它具有“语义”,在分页分页器中没有逻辑...并尽可能避免使用原始查询,始终使用模型,并且仅在您有一个非常复杂的查询并且Eloquent无法解决它或比纯SQL更难阅读时才使用DB
。 - matiaslauriti