2016-07-01 69 views
6

我有搜索多個模型的搜索方法。爲了簡單起見,我添加了兩個我正在搜索的模型。如何在Laravel中對多個模型進行分頁

我想結合這兩個模型來分析他們的結果。

這是我目前正在做的。

public function search(Request $request) 
{ 
    $query = $request->get('q'); 
    $threads = Thread::where('title', 'LIKE', "%{$query}%")->get(); 
    $posts = Post::where('body', 'LIKE', "%{$query}%")->get(); 
    $results = array_merge($threads->toArray(), $posts->toArray()); 
    $results = new Paginator($results, 10); 

    return view('pages.search', compact('query', 'results')); 
} 

這有效,但我覺得這是真的效率低下,可以改進。有一個更好的方法嗎?

回答

6

試試這個控制器,

<?php namespace App\Http\Controllers; 
use Illuminate\Pagination\LengthAwarePaginator; 
use Illuminate\Support\Collection; 

class SearchController extends Controller { 
public function search(Request $request){ 
    $query = $request->get('q'); 
    $threads = Thread::where('title', 'LIKE', "%{$query}%")->get(); 
    $posts = Post::where('body', 'LIKE', "%{$query}%")->get(); 
    $searchResults = array_merge($threads->toArray(), $posts->toArray()); 
    //Get current page form url e.g. &page=6 
    $currentPage = LengthAwarePaginator::resolveCurrentPage(); 

    //Create a new Laravel collection from the array data 
    $collection = new Collection($searchResults); 

    //Define how many items we want to be visible in each page 
    $perPage = 10; 

    //Slice the collection to get the items to display in current page 
    $currentPageSearchResults = $collection->slice($currentPage * $perPage, $perPage)->all(); 

    //Create our paginator and pass it to the view 
    $paginatedSearchResults= new LengthAwarePaginator($currentPageSearchResults, count($collection), $perPage); 

    return view('pages.search', compact('query', '$searchResults')); 
} 
} 

在你看來,search.blade.php

<?php echo $query->render(); ?> 

Reference

+0

代碼中存在一個錯誤。它應該是切片(($ currentPage-1)* $ perPage)。否則,你永遠不會得到第一個結果。 –

-1

您可以檢查'DataTables',以便從前端側分頁數據。 https://datatables.net/

+0

這是無關的字體​​結束。請再次閱讀該問題。 – Enijar

相關問題