Codeigniter 4 Pagination with join tables showing error

廉价感情. 提交于 2021-01-29 06:44:34

问题


I am working on codeigniter project. I am showing news table with join left news category and paginate. When I tried the below code I get an error Call to undefined method CodeIgniter\Database\MySQLi\Builder::paginate(). How to show news data with join and pagination?

    $db      = \Config\Database::connect();
    $news_tbl = $db->table('tbl_news')->join('tbl_category', 'tbl_news.category_id = tbl_category.category_id');
    $data['news_fetched'] = $news_tbl->paginate(10);
    $data['pager'] = $news_fetched->pager;
    $data['links'] = $data['pager']->links();

回答1:


$db->table() creates a query builder object. Pagination works with model objects. You're not setting your pagination the right way. You should create a Model file called tblNewsModel that will handle pagination for you.

<?php
namespace App\Models;

class tblNewsModel extends \CodeIgniter\Model {

    protected $table = 'tbl_news';
    protected $primaryKey = 'your_pk_id';

    // your function to paginate
    public function paginateNews(int $nb_page) {
        return $this->select()->join('tbl_category', 'tbl_news.category_id = tbl_category.category_id')->paginate($nb_page);
    }

}

And then in your controller, just create a new instance of this model and ask him to give you the pagination

$tblNewsModel = new \App\Models\tblNewsModel();
$data['news_fetched'] = $tblNewsModel->paginateNews(10);
$data['pager'] = $tblNewsModel->pager;
$data['links'] = $data['pager']->links();


来源:https://stackoverflow.com/questions/65275626/codeigniter-4-pagination-with-join-tables-showing-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!