2016-07-01 20 views
6

Birden çok modeli arayan bir arama yöntemim var. Basitlik için aradığım iki model ekledim.Laravel'de Birden Fazla Model Nasıl Salgılanır

İki modeli birleştirerek sonuçlarını paginate etmek istiyorum.

İşte şu anda yapıyorum.

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

Bu işler, ancak bunun gerçekten verimsiz olduğunu ve geliştirilebileceğini hissediyorum. Bunu yapmanın daha iyi bir yolu var mı?

cevap

6

bu denetleyici deneyin , Kişisel görünümünde

<?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

Kodda bir hata var. Dilim olmalıdır (($ currentPage-1) * $ perPage). Aksi halde ilk sonuçları asla alamazsınız. –

-1

'DataTables' öğesini ön uçtan kolay paginate veriler olarak kontrol edebilirsiniz. https://datatables.net/

+0

Bu yazı ucuyla ilgisi olduğunu. Lütfen soruyu tekrar okuyun. – Enijar

İlgili konular