tp5 fastadmin hasmany一对多关联并求值排序
短信预约 -IT技能 免费直播动态提醒
一对多关联并求值排序
**
- 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
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341