laravel 如何在DB原始复杂查询中使用分页

6ljaweal  于 2023-04-13  发布在  其他
关注(0)|答案(2)|浏览(142)

请帮助我的家伙使用分页类的laravel与数据库原始复杂的查询...
尝试了一些技巧来获得结果与laravel分页,但由于查询的复杂性,它创造了问题,我

$data = DB::select(DB::raw("SELECT DISTINCT c.id, c.name, c.active, c.image, c.created_at, (SELECT COUNT(*) FROM categories WHERE c.id=parent_id) AS subcat_count, (SELECT COUNT(*) FROM post_ads WHERE c.id=cat_id) AS postad_count FROM categories AS c LEFT OUTER JOIN categories AS subc ON c.id = subc.parent_id LEFT OUTER JOIN post_ads AS postadc ON c.id = postadc.cat_id WHERE c.parent_id=0 ORDER BY c.name ASC LIMIT 9"));
hivapdat

hivapdat1#

使用限制和偏移而不是分页,我有同样的问题,并解决了它通过使用限制和偏移。

$limit = 10;
$offset = 0; //change it dynamically

$data = DB::select(DB::raw("SELECT DISTINCT c.id, c.name, c.active, c.image, c.created_at, (SELECT COUNT(*) FROM categories WHERE c.id=parent_id) AS subcat_count, (SELECT COUNT(*) FROM post_ads WHERE c.id=cat_id) AS postad_count FROM categories AS c LEFT OUTER JOIN categories AS subc ON c.id = subc.parent_id LEFT OUTER JOIN post_ads AS postadc ON c.id = postadc.cat_id WHERE c.parent_id=0 ORDER BY c.name ASC LIMIT $limit OFFSET $offset"));
a2mppw5e

a2mppw5e2#

你可以使用长度感知分页器分页,在你的控制器中这样做,

use Illuminate\Pagination\LengthAwarePaginator;
...
class StudentAvailablitiesController extends Controller
{
   public function index()
   {
       $collection = DB::select(DB::raw...)->get();
       $paginatedData = $collection->paginate(10);
   }

   public function paginate($perPage, $total = null, $page = null, $pageName = 'page')
   {
        $page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);

        return new LengthAwarePaginator(
            $this->forPage($page, $perPage),
            $total ?: $this->count(),
            $perPage,
            $page,
            [
                'path' => LengthAwarePaginator::resolveCurrentPath(),
                'pageName' => $pageName,
            ]
        );
    }
}

相关问题