thinkphp5提供了withCount()方法来封装withSum(),并调用
来封装hasMany()、hasOne()等。如果有两张表,user(用户表)和order(订单表),我们需要对每个用户订单中的fee字段进行求和。
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; }
HasMany.php 添加:
public function getRelationSumQuery($closure, $sum) { if ($closure) { call_user_func_array($closure, [ & $this->query]); } $localKey = $this->localKey ?: $this->parent->getPk(); return $this->query->whereExp($this->foreignKey, '=' . $this->parent->getTable() . '.' . $localKey)->fetchSql()->sum($sum); }
调用方法:
$data = model('user')->withSum('order', 'fee')->select();
widthSum('order'),其中order是指模型中为hasMany添加的方法。
public function order() { return $this->hasMany('Order'); }
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。