1.Query.php 文件中添加如下方法:
/**
* @param $relation model中关联方法
* @param bool $subQuery 是否是有子查询
* @param string $sum 统计生成后缀
* @param bool $left_alias 左表别名
* @return $this
*/
public function withSum($relation, $subQuery = true, $sum='num',$left_alias=false)
{
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 = '(' . (new $this->model)->$relation()->getRelationSumQuery($closure, $sum,$left_alias) . ')';
$this->field([$count => Loader::parseName($relation) . '_sum']);
}
}
return $this;
}
2.HasMany.php中添加如下方法:
public function getRelationSumQuery($closure, $sum,$left_alias)
{
if($left_alias)
{
$table = $left_alias;
}
else
{
$table = $this->parent->getTable();
}
if ($closure) {
call_user_func_array($closure, [ & $this->query]);
}
return $this->query->where([
$this->foreignKey => [
'exp',
'=' . $table . '.' . $this->parent->getPk(),
],
])->fetchSql()->sum($sum);
}
3.model 中添加关联 如
//自定义统计求和
public function stock()
{
return $this->hasMany('Stock','device_id');
}
4.逻辑中调用:
$result = $this->modelDevice
->alias('a')
->withSum('stock',true,'num','a')//自定义统计sum方法
->join($join)
->where($where)
->field($field)
->order($order)
->paginate($paginate);
withSum('stock',true,'num','a') 参数说明
stock model 中关联方法
true 是否使用字查询
num 查询完成后 字段为 stock_num
a 如果存在alias 设置 关联sum的左表 alias