欢迎您访问我的笔记本站旨在于记录一些平时工作中遇到的一些问题和解决方法,方便查阅,部分内容来源于网络,如有侵权请联系我删除
  • 微信微信
您现在的位置是:首页 > PHP后端

TP5 DISTINCT 方法分页问题-[原创]

日期:2021-06-22 16:32:46 作者:tanyi 来源:我的笔记 浏览:819 次
DISTINCT 方法用于返回唯一不同值,而tp在使用DISTINCT 方法时分页会有一些问题,分页统计的总数与查询的总数不一致导致分页异常,下面是针对tp5做的一些小改动来应对这个问题

首先定位到Query.php的paginate方法,然后顺藤摸瓜

image.png

image.png

image.png

echo 输出$aggregate . '(' . (!empty($distinct) ? 'DISTINCT ' : '') . $field . ') AS tp_' . strtolower($aggregate)

image.png

到此基本不用往下看了,后面就是组装sql执行这些。找到这一步就很简单了,想办法把COUNT(*) AS tp_count改成我们自己想要的就行,比如COUNT(DISTINCT xxx) AS tp_count,DISTINCT后面必须跟字段名,不能直接写一个*,会报错,如COUNT(DISTINCT user_name) AS tp_count;为了最大限度不影响框架本身,于是新加一个函数来做处理,下面是代码。

image.png

image.png

image.png

/**
 * @param $str 字段名,如user_name a.user_name
 * @return $this
 */
public function distinct_count($str){
    $this->options['distinct_count'] = $str;
    return $this;
}


/**
 * 聚合查询
 * @access public
 * @param  string $aggregate    聚合方法
 * @param  string $field        字段名
 * @param  bool   $force        强制转为数字类型
 * @return mixed
 */
public function aggregate($aggregate, $field, $force = false)
{
    if (0 === stripos($field, 'DISTINCT ')) {
        list($distinct, $field) = explode(' ', $field);
    }
    if (!preg_match('/^[\w\.\+\-\*]+$/', $field)) {
        throw new Exception('not support data:' . $field);
    }
    if(strlen($this->options['distinct_count'] ?? '')){
        $result = $this->value($aggregate . '(DISTINCT '.$this->options['distinct_count'].') AS tp_' . strtolower($aggregate), 0, $force);
    }else{
        $result = $this->value($aggregate . '(' . (!empty($distinct) ? 'DISTINCT ' : '') . $field . ') AS tp_' . strtolower($aggregate), 0, $force);
    }
    return $result;
}


提交评论
评论列表