一对多关联并求值排序
**
- Query.php 添加//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;}
HasMany.php 添加://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(); return $this->query->whereExp($this->foreignKey, '=' . $this->parent->getTable() . '.' . $localKey)->fetchSql()->sum($sum); }
控制器添加调用
public function index() { //当前是否为关联查询 $this->relationSearch = false; //设置过滤方法 $this->request->filter(['strip_tags', 'trim']); if ($this->request->isAjax()) { //如果发送的来源是Selectpage,则转发到Selectpage if ($this->request->request('keyField')) { return $this->selectpage(); } list($where, $sort, $order, $offset, $limit) = $this->buildparams(); $list =$this->model ->withSum('ceshi1',true, 'num')//关联获取总值 ->where($where) ->order($sort, $order) ->paginate($limit); $result = array("total" => $list->total(), "rows" => $list->items()); return json($result); } return $this->view->fetch(); }
在对应model里面添加
public function ceshi1(){ return $this->hasMany('ceshi1','ceshi_id'); }
在对应js里面添加
table.bootstrapTable({ url: $.fn.bootstrapTable.defaults.extend.index_url, pk: 'id', sortName: 'ceshi1_sum',//排序的字段 sortOrder: 'desc',//倒叙 columns: [ [ {checkbox: true}, {field: 'id', title: __('Id')}, {field: 'name', title: __('Name'), operate: 'LIKE'}, {field: 'ceshi1_sum', title: __('Num')}, {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate} ] ] });
来源地址:https://blog.csdn.net/qq_42958118/article/details/127641476