Codeigniter 4连接表分页显示错误

5gfr0r5j  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(125)

我正在进行codeigniter项目。我正在显示带有join左新闻类别和分页的新闻表。当我尝试下面的代码时,我得到了一个错误Call to undefined method CodeIgniter\Database\MySQLi\Builder::paginate()。如何显示带有join和分页的新闻数据?

$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();
gudnpqoy

gudnpqoy1#

$db->table()创建一个查询生成器对象。分页与模型对象一起使用。您没有以正确的方式设置分页。您应该创建一个名为tblNewsModel的模型文件来处理分页。

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

}

然后在你的控制器中,创建一个这个模型的新示例,让他给予你分页

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

相关问题