想要的效果:
而不是 $a['pm] = ['pm' ,'cover','power'] 这种形式.
对应的方法!
public function withAttr($name, callable $callback = null){if (is_array($name)) {foreach ($name as $key => $val) {$this->withAttr($key, $val);}return $this;}$this->options['with_attr'][$name] = $callback;if (strpos($name, '.')) {[$relation, $field] = explode('.', $name);if (!empty($this->options['json']) && in_array($relation, $this->options['json'])) {} else {$this->options['with_relation_attr'][$relation][$field] = $callback;unset($this->options['with_attr'][$name]);}}return $this;}
public function append(array $append = []){$this->options['append'] = $append;return $this;}
public function page(): array{$builder = new Builder($this->getModel());$builder->setOp(['create_time' => 'DATE_RANGE']);return $builder->selectQuery(function (BaseQuery $query) {//关联查询-开始$query->append(['pm','power','cover'])->withAttr(['pm' => function ($v, $r) {//获取榜单排名$tx = [];$data = (new RechargeModel())->with(['user'])->where('list_id',$r['id'])->field('user_id,SUM(money) as money')->group('user_id')->order('money','desc')->limit(4)->select()->toArray();if(count($data)){foreach ($data as $item){$tx[]= $item['user'];}}return $tx;},'power' => function ($v, $r) {$cover = (new InfoModel())->where('id',$r['id'])->find();$power = (new TypeModel())->where('id',$cover['lx'])->find();return $power['power'];},'cover' => function ($v, $r) {$cover = (new InfoModel())->where('id',$r['id'])->find();return $cover['cover'];},]);$with = array_merge($with ?? [], ['user', 'info', 'plan']); $query->with($with);//关联查询-结束})->page();}}