ApiTextbook.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Eloquent\Collection;
  5. class ApiTextbook extends Model
  6. {
  7. // 使用不存在的表名,完全禁用 MySQL 查询
  8. protected $table = 'api_textbooks_external_data_source';
  9. protected $primaryKey = 'id';
  10. public $timestamps = false;
  11. // 禁用所有数据库操作
  12. public static function on($connection = null)
  13. {
  14. throw new \Exception('External data source - database queries disabled');
  15. }
  16. public static function onWriteConnection()
  17. {
  18. throw new \Exception('External data source - database queries disabled');
  19. }
  20. protected $fillable = [
  21. 'id', 'series_id', 'series', 'stage', 'grade', 'semester',
  22. 'naming_scheme', 'track', 'module_type', 'volume_no',
  23. 'legacy_code', 'curriculum_standard_year', 'curriculum_revision_year',
  24. 'approval_year', 'edition_label', 'official_title', 'display_title',
  25. 'aliases', 'isbn', 'cover_path', 'status', 'created_at'
  26. ];
  27. protected $casts = [
  28. // 移除所有 array cast,直接使用 JSON 字符串
  29. ];
  30. public function __construct(array $attributes = [])
  31. {
  32. foreach ($attributes as $key => $value) {
  33. $this->setAttribute($key, $value);
  34. }
  35. parent::__construct($attributes);
  36. }
  37. /**
  38. * 获取系列信息
  39. */
  40. public function getSeriesAttribute($value)
  41. {
  42. if (is_array($value)) {
  43. return (object) $value;
  44. }
  45. return $value;
  46. }
  47. /**
  48. * 从 API 获取所有数据
  49. */
  50. public static function fromApi($page = 1, $perPage = 10)
  51. {
  52. $apiService = app(\App\Services\TextbookApiService::class);
  53. $params = [
  54. 'page' => $page,
  55. 'per_page' => $perPage,
  56. ];
  57. $result = $apiService->getTextbooks($params);
  58. // 返回 Eloquent 模型实例(但禁用数据库查询)
  59. $records = [];
  60. foreach ($result['data'] ?? [] as $item) {
  61. $records[] = new static($item);
  62. }
  63. return new Collection($records);
  64. }
  65. /**
  66. * 从 API 获取总数
  67. */
  68. public static function countFromApi()
  69. {
  70. $apiService = app(\App\Services\TextbookApiService::class);
  71. $params = ['page' => 1, 'per_page' => 1];
  72. $result = $apiService->getTextbooks($params);
  73. return $result['meta']['total'] ?? 0;
  74. }
  75. /**
  76. * 覆盖查询构建器方法,防止数据库查询
  77. */
  78. public function newQuery()
  79. {
  80. throw new \Exception('External data source - use getTableRecords() instead');
  81. }
  82. public static function query()
  83. {
  84. throw new \Exception('External data source - use getTableRecords() instead');
  85. }
  86. }