沃梦达 / 编程问答 / php问题 / 正文

如何在 Laravel DB::select 查询中使用分页

How to use pagination with laravel DB::select query(如何在 Laravel DB::select 查询中使用分页)

本文介绍了如何在 Laravel DB::select 查询中使用分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Laravel 中开展一个项目,并使用 DB Facade 运行 sql 的原始查询.就我而言,我使用的是 DB::select,问题是分页方法不适用于此 DB 原始查询并显示此错误

I am working on a project in Laravel and using DB facade to run raw queries of sql. In my case I am using DB::select, problem is that pagination method is not working with this DB raw query and showing this error

Call to a member function paginate() on array

我只想知道如何使用 DB 原始查询实现 Laravel 分页这是我的代码:

I just want how to implement laravel pagination with DB raw queries here is my code:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppNotice;
use IlluminateSupportFacadesDB;
use IlluminatePaginationPaginator;
use IlluminatePaginationLengthAwarePaginator;

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

这篇关于如何在 Laravel DB::select 查询中使用分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 Laravel DB::select 查询中使用分页

基础教程推荐