【问题标题】:Codeigniter 4 Search Pagination not counting and returning pageCodeigniter 4搜索分页不计数并返回页面
【发布时间】:2022-01-07 22:42:32
【问题描述】:

我正在做一个简单的搜索项目,我正在返回结果。搜索功能似乎可以工作,但是总和页面返回错误的值。 total 字段返回数据中的总行数,而不是搜索结果的总数,并且页面始终为 {}。

这是我创建的模型->函数:

 public function search($string)
{

    $results = $this->select('*')->orLike('title', $string)->orLike('excerpt', $string);

    if ( empty( $results ) )
    {
        return [];
    
    } else 
    {
        $data = [
            'results' => $results->paginate(2),
            'total'   => $results->countAllResults(),
            'page'    => $this->pager,
            
        ];

        return $data;

    }
}

令人费解的是,如果我将总字段放在计数有效的结果值之上,但结果字段会在 paginate(2) 处返回数据库中的所有内容。

【问题讨论】:

  • paginate 似乎是一个自定义函数。你做到了吗?
  • 没有通过 CI 4 中的查询 API 传递分页
  • 您可能想检查一下,因为我知道分页类,但不是名为 paginate() 的函数。 countAllResults 也看起来像一个自定义函数(一个简单的count($results) 解决了这个问题)。我很好奇您如何使用单个 $this 调用数据库。通常db类是一个单独的项目,所以$this->db$db...但我从来没有把它称为$this
  • 通过use CodeIgniter\Model; 使用模型时,您可以直接访问数据库以及其他一些好东西,而无需额外的绒毛。见codeigniter.com/user_guide/models/model.html。我之前设法解决了这个问题,所以我会更新这个问题

标签: php codeigniter search codeigniter-4


【解决方案1】:

好的,我设法通过向数据库添加两个单独的查询来解决此查询。处理成本似乎很小,缓存响应时应该没问题。事实证明,您可以链接查询,但只能按特定顺序并且如果您使用分组(请参阅 ->groupStart() )

  $results = $this->select('title, image, categories, id, excerpt')->groupStart()->like('title', $search)->orLike('excerpt', $search)->groupEnd()->where('status','live')->paginate(2);
  $total   = $this->select('title, image, categories, id, excerpt')->groupStart()->like('title', $search)->orLike('excerpt', $search)->groupEnd()->where('status','live')->countAllResults();

有些人可能会争辩这两个查询效率低下,但这适用于我的用例 :) 希望这可以帮助其他遇到类似问题的人。

【讨论】:

    猜你喜欢
    • 2013-03-05
    • 1970-01-01
    • 2016-06-15
    • 2012-05-15
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    相关资源
    最近更新 更多