2017-05-20 18 views
3

私はLaravelのプロジェクトでDBファサードを使ってsqlの生のクエリを実行しています。 私の場合は、DB ::選択を使用しています、問題は、ページネーション方式は、これは生のクエリをDBで作業し、このエラーにlaravelでページ設定を使用する方法DB :: select query

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

答えて

3

は試してみてください。

$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); 
+0

ありがとうございます@ MohammadSabil83 ...これは魅力的です –

+0

あなたのコードはlaravel ... 再度、感謝します –

9
public function index(Request $request){ 

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

$notices = $this->arrayPaginator($notices, $request); 

return view('welcome')->with('allNotices', $notices); 

} 

public function arrayPaginator($array, $request) 
{ 
    $page = Input::get('page', 1); 
    $perPage = 10; 
    $offset = ($page * $perPage) - $perPage; 

    return new LengthAwarePaginator(array_slice($array, $offset, $perPage, true), count($array), $perPage, $page, 
     ['path' => $request->url(), 'query' => $request->query()]); 
} 
+0

にです私の一日を救った。組み込みpaginate()関数の偉大なカスタマイズ。 Hightは兄弟に感謝しました。 –

+0

おかげさまでここにたくさんありがとうございました。私のクエリにはいくつかの計算があり、通常の方法では動作しません。 –

関連する問題