简体   繁体   中英

How to use Laravel pagination with Sphinx

In my search controller I use Sphinx for fetching the results. It looks like this:

    $cl = new SphinxSearch();

    $results = $cl->setMatchMode(\Sphinx\SphinxClient::SPH_MATCH_EXTENDED);
    $results = $cl->setSortMode(\Sphinx\SphinxClient::SPH_SORT_ATTR_DESC, "start");
    $results = $cl->search('@*' . $name, 'spots');
    $results = $cl->get();

It shows me a couple of hundred results and it is really heavy to load. I know that the Laravel has feature for pagination ( https://laravel.com/docs/5.4/pagination ), but I don't know how to use it with this Sphinx package. BTW I use this one - https://github.com/sngrl/sphinxsearch

Any suggestion?

You can create paginator using Sphinx results. After getting paginated results from Sphinx.

    $paginator = new LengthAwarePaginator(
        $results,
        $totalResultsCount,
        $perPage,
        $currentPage
    );
    $paginator->setCollection(collect($results));

When manually creating a paginator instance, you should manually "slice" the array of results you pass to the paginator. So a method from a controller would look like this:

public function doSearch()
{
    $template = 'search/search_results';
    $filters = Input::get('filter');
    $currentPage = Input::get('page') ? Input::get('page') : 1;
    $perPage = 5;
    // prepare $sphinxQuery using the filters received
    $results = SphinxSearch::search($sphinxQuery, 'indexname')
        ->setFieldWeights(
            array(
                    'name' => 10,
            )
        )
        ->setMatchMode(SphinxClient::SPH_MATCH_EXTENDED)
        ->setSortMode(SphinxClient::SPH_SORT_EXTENDED, "name ASC")
        ->limit(1000)
        ->get(true);
    $paginator = new LengthAwarePaginator(
        collect($results)->forPage($currentPage, $perPage), sizeof($results), $perPage, $currentPage
    );
    $paginator->setPath(route('name.of.the.route'));
    $paginator->setPageName('page');  
    $data['items'] = $paginator;  

    return View::make($template, $data);
}

And in the blade template:

<?php echo $items->appends(['filter' => Request::get('filter')])->render(); ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM