Textbook.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. class Textbook extends Model
  5. {
  6. protected $table = 'textbooks';
  7. protected $fillable = [
  8. 'id',
  9. 'series_id',
  10. 'stage',
  11. 'schooling_system',
  12. 'grade',
  13. 'semester',
  14. 'naming_scheme',
  15. 'track',
  16. 'module_type',
  17. 'volume_no',
  18. 'legacy_code',
  19. 'curriculum_standard_year',
  20. 'curriculum_revision_year',
  21. 'approval_authority',
  22. 'approval_year',
  23. 'edition_label',
  24. 'official_title',
  25. 'aliases',
  26. 'isbn',
  27. 'cover_path',
  28. 'status',
  29. 'sort_order',
  30. 'meta',
  31. 'series',
  32. 'created_at',
  33. 'updated_at',
  34. ];
  35. protected $casts = [
  36. 'aliases' => 'array',
  37. 'meta' => 'array',
  38. 'grade' => 'integer',
  39. 'semester' => 'integer',
  40. 'volume_no' => 'integer',
  41. 'curriculum_standard_year' => 'integer',
  42. 'curriculum_revision_year' => 'integer',
  43. 'approval_year' => 'integer',
  44. 'sort_order' => 'integer',
  45. ];
  46. public function __construct(array $attributes = [])
  47. {
  48. parent::__construct($attributes);
  49. // 从 API 数据初始化时设置属性
  50. foreach ($attributes as $key => $value) {
  51. $this->setAttribute($key, $value);
  52. }
  53. }
  54. public function series()
  55. {
  56. return $this->belongsTo(TextbookSeries::class, 'series_id', 'id');
  57. }
  58. public function catalogs()
  59. {
  60. return $this->hasMany(TextbookCatalog::class);
  61. }
  62. /**
  63. * 获取系列信息(兼容 API 返回的嵌套对象)
  64. */
  65. public function getSeriesAttribute($value)
  66. {
  67. if (is_array($value)) {
  68. return (object) $value;
  69. }
  70. return $value;
  71. }
  72. public function getSeriesNameAttribute(): string
  73. {
  74. if ($this->relationLoaded('series') && $this->series) {
  75. return $this->series->name ?? '未归类系列';
  76. }
  77. $seriesId = $this->series_id;
  78. if (!$seriesId) {
  79. return '未归类系列';
  80. }
  81. static $seriesMap = null;
  82. if ($seriesMap === null) {
  83. $seriesMap = TextbookSeries::query()
  84. ->pluck('name', 'id')
  85. ->toArray();
  86. }
  87. return $seriesMap[$seriesId] ?? '未归类系列';
  88. }
  89. }