1、在 thinkphp\library\think\db\Query.php
中添加:
public function withSum($relation, $subQuery = true, $sum='sum')
{
if (!$subQuery) {
$this->options['with_sum'] = $relation;
} else {
$relations = is_string($relation) ? explode(',', $relation) : $relation;
if (!isset($this->options['field'])) {
$this->field('*');
}
foreach ($relations as $key => $relation) {
$closure = false;
if ($relation instanceof \Closure) {
$closure = $relation;
$relation = $key;
}
$relation = Loader::parseName($relation, 1, false);
$count = '(' . $this->model->$relation()->getRelationSumQuery($closure, $sum) . ')';
$this->field([$count => Loader::parseName($relation) . '_sum']);
}
}
return $this;
}
2、在 thinkphp\library\think\model\relation\HasMany.php
中添加:
public function getRelationSumQuery($closure, $sum)
{
if ($closure) {
call_user_func_array($closure, [ & $this->query]);
}
$localKey = $this->localKey ?: $this->parent->getPk();
$parentTable = $this->parent->getTable();
$options = $this->parent->getOptions();
if(isset($options['alias'][$parentTable])){
$parentTable = $options['alias'][$parentTable];
}
return $this->query->whereExp($this->foreignKey, '=' . $parentTable . '.' . $localKey)->fetchSql()->sum($sum);
}