【发布时间】:2017-10-20 18:50:07
【问题描述】:
我正在 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。
标签: php mysql laravel pagination