| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- <?php
- namespace App\Models;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Database\Eloquent\Collection;
- class ApiTextbook extends Model
- {
- // 使用不存在的表名,完全禁用 MySQL 查询
- protected $table = 'api_textbooks_external_data_source';
- protected $primaryKey = 'id';
- public $timestamps = false;
- // 禁用所有数据库操作
- public static function on($connection = null)
- {
- throw new \Exception('External data source - database queries disabled');
- }
- public static function onWriteConnection()
- {
- throw new \Exception('External data source - database queries disabled');
- }
- protected $fillable = [
- 'id', 'series_id', 'series', 'stage', 'grade', 'semester',
- 'naming_scheme', 'track', 'module_type', 'volume_no',
- 'legacy_code', 'curriculum_standard_year', 'curriculum_revision_year',
- 'approval_year', 'edition_label', 'official_title', 'display_title',
- 'aliases', 'isbn', 'cover_path', 'status', 'created_at'
- ];
- protected $casts = [
- // 移除所有 array cast,直接使用 JSON 字符串
- ];
- public function __construct(array $attributes = [])
- {
- foreach ($attributes as $key => $value) {
- $this->setAttribute($key, $value);
- }
- parent::__construct($attributes);
- }
- /**
- * 获取系列信息
- */
- public function getSeriesAttribute($value)
- {
- if (is_array($value)) {
- return (object) $value;
- }
- return $value;
- }
- /**
- * 从 API 获取所有数据
- */
- public static function fromApi($page = 1, $perPage = 10)
- {
- $apiService = app(\App\Services\TextbookApiService::class);
- $params = [
- 'page' => $page,
- 'per_page' => $perPage,
- ];
- $result = $apiService->getTextbooks($params);
- // 返回 Eloquent 模型实例(但禁用数据库查询)
- $records = [];
- foreach ($result['data'] ?? [] as $item) {
- $records[] = new static($item);
- }
- return new Collection($records);
- }
- /**
- * 从 API 获取总数
- */
- public static function countFromApi()
- {
- $apiService = app(\App\Services\TextbookApiService::class);
- $params = ['page' => 1, 'per_page' => 1];
- $result = $apiService->getTextbooks($params);
- return $result['meta']['total'] ?? 0;
- }
- /**
- * 覆盖查询构建器方法,防止数据库查询
- */
- public function newQuery()
- {
- throw new \Exception('External data source - use getTableRecords() instead');
- }
- public static function query()
- {
- throw new \Exception('External data source - use getTableRecords() instead');
- }
- }
|