logic = $logic; } /** * 列表接口 * 支持前端直接传递: * - filter_* → where * - sort_by, order * - fields (逗号分隔) * - with (逗号分隔) * - withFields (relation:field,field;...) * - dataLimitType, dataLimitField * - limit, page * - complex_query=1 则调用 complexQuery() */ public function list(Request $request): array { $p = $request->get(); // 复杂查询开关 if (!empty($p['complex_query']) && method_exists($this, 'complexQuery')) { return $this->complexQuery($p); } // 1. 构造 where $where = []; foreach ($p as $k => $v) { if (strpos($k, 'filter_') === 0 && $v !== '') { $col = substr($k, 7); // 简单等值或 like $where[$col] = strpos($v, '%') !== false ? ['like', $v] : $v; } } // 2. 构造其他配置 $config = [ 'where' => $where, 'order' => [($p['sort_by'] ?? 'id') => ($p['order'] ?? 'desc')], 'fields' => !empty($p['fields']) ? explode(',', $p['fields']) : [], 'with' => !empty($p['with']) ? explode(',', $p['with']) : [], 'withFields' => $this->parseWithFields($p['withFields'] ?? ''), 'dataLimit' => !empty($p['dataLimitType']) ? [ 'type' => $p['dataLimitType'], 'field' => $p['dataLimitField'] ?? 'admin_id' ] : [], ]; $limit = (int)($p['limit'] ?? 15); $page = (int)($p['page'] ?? 1); $pager = $this->logic->list($config, $limit, $page); return ['total' => $pager->total(), 'data' => $pager->items()]; } /** * 详情 */ public function show($id) { return $this->logic->show($id, []); } /** * 创建 */ public function store(Request $request) { $data = $request->post(); $dataLimit = $this->getDataLimitFromRequest($request); return $this->logic->create($data, $dataLimit); } /** * 更新 */ public function update(Request $request) { $key = $this->logic->modelClass::make()->getKeyName(); $id = (int)$request->post($key); $data= $request->post(); $dataLimit = $this->getDataLimitFromRequest($request); return $this->logic->updateByPk($id, $data, $dataLimit); } /** * 删除 */ public function destroy(Request $request) { $key = $this->logic->modelClass::make()->getKeyName(); $ids = (array)$request->post($key, []); return $this->logic->deleteByPk($ids); } /** ---------- helpers ---------- */ /** * 解析 withFields 参数 "rel:field,field;rel2:..." */ protected function parseWithFields(string $str): array { if (!$str) return []; $out = []; foreach (explode(';', $str) as $pair) { [$rel, $flds] = explode(':', $pair); $out[$rel] = explode(',', $flds); } return $out; } /** * 从请求里读取 dataLimitType/Field */ protected function getDataLimitFromRequest(Request $req): array { $type = $req->get('dataLimitType'); if (!$type) return []; return [ 'type' => $type, 'field' => $req->get('dataLimitField', 'admin_id'), ]; } /** * 子类可重写,做复杂联表查询等 */ protected function complexQuery(array $params): array { throw new \LogicException('请在子类实现 complexQuery 方法'); } }