db->one("SELECT * FROM `{$table}` WHERE id = ?", [$id]) ?? throw new ApiError(404, '记录不存在'); } public function requireReference(string $table, int $id, string $label): array { return $this->db->one("SELECT * FROM `{$table}` WHERE id = ?", [$id]) ?? throw new ApiError(422, $label . '不存在'); } public function insert(string $table, array $values): int { $columns = implode(',', array_map(static fn ($key) => '`' . $key . '`', array_keys($values))); $marks = implode(',', array_fill(0, count($values), '?')); $this->db->execute("INSERT INTO `{$table}` ({$columns}) VALUES ({$marks})", array_values($values)); return (int) $this->db->pdo->lastInsertId(); } public function update(string $table, int $id, array $values): void { $columns = implode(',', array_map(static fn ($key) => '`' . $key . '` = ?', array_keys($values))); $this->db->execute("UPDATE `{$table}` SET {$columns} WHERE id = ?", [...array_values($values), $id]); } public function ids(string $table, string $ownerField, int $id, string $valueField): array { return array_map('intval', array_column($this->db->all("SELECT `{$valueField}` FROM `{$table}` WHERE `{$ownerField}` = ? ORDER BY `{$valueField}`", [$id]), $valueField)); } public function replace(string $table, string $ownerField, int $id, string $valueField, array $values): void { $this->db->execute("DELETE FROM `{$table}` WHERE `{$ownerField}` = ?", [$id]); foreach ($values as $value) { $this->db->execute("INSERT INTO `{$table}` (`{$ownerField}`,`{$valueField}`) VALUES (?,?)", [$id, $value]); } } public function associations(string $table, array $ids, array $existing = []): void { foreach ($ids as $id) { $record = $this->requireReference($table, $id, $table === 'system_role' ? '角色' : '部门'); if ((int) $record['disable'] === 1 && !in_array($id, $existing, true)) { throw new ApiError(422, '不能新增关联已停用的角色或部门'); } } } public function publicAdmin(array $row): array { $id = (int) $row['id']; $roles = $this->db->all('SELECT r.id,r.name FROM system_role r JOIN admin_role ar ON ar.role_id=r.id WHERE ar.admin_id=? ORDER BY r.id', [$id]); $depts = $this->db->all('SELECT d.id,d.name FROM dept d JOIN admin_dept ad ON ad.dept_id=d.id WHERE ad.admin_id=? ORDER BY d.id', [$id]); return [ 'id' => $id, 'account' => $row['account'], 'name' => $row['name'], 'is_root' => (int) $row['is_root'], 'disable' => (int) $row['disable'], 'role_id' => array_map('intval', array_column($roles, 'id')), 'role_names' => array_column($roles, 'name'), 'dept_id' => array_map('intval', array_column($depts, 'id')), 'dept_names' => array_column($depts, 'name'), 'create_time' => (int) $row['create_time'], ]; } public function publicRole(array $row): array { return ['id' => (int) $row['id'], 'name' => $row['name'], 'desc' => $row['desc'], 'sort' => (int) $row['sort'], 'disable' => (int) $row['disable'], 'menu_id' => $this->ids('system_role_menu', 'role_id', (int) $row['id'], 'menu_id')]; } }