我正在Laravel中进行一个项目,并使用DB Facade来运行sql的原始查询。
就我而言,我使用的是DB::select,问题是分页方法不适用于此数据库原始查询并显示此错误
Call to a member function paginate() on array
我只想如何使用数据库原始查询实现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);
}
}
最佳答案
尝试:
$notices = DB::table('notices')
->join('users', 'notices.user_id', '=', 'users.id')
->join('departments', 'users.dpt_id', '=', 'departments.id')
->select('notices.id', 'notices.title', 'notices.body', 'notices.created_at', 'notices.updated_at', 'users.name', 'departments.department_name')
->paginate(20);