Textbook.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. public function getSeriesNameAttribute(): string
  63. {
  64. $seriesName = $this->getAttributeFromArray('series_name');
  65. if (filled($seriesName)) {
  66. return (string) $seriesName;
  67. }
  68. if ($this->relationLoaded('series') && $this->getRelation('series')) {
  69. return $this->getRelation('series')->name ?? '未归类系列';
  70. }
  71. $series = $this->series()->first();
  72. if ($series) {
  73. return $series->name ?? '未归类系列';
  74. }
  75. $seriesId = $this->series_id;
  76. if (!$seriesId) {
  77. return '未归类系列';
  78. }
  79. static $seriesMap = null;
  80. if ($seriesMap === null) {
  81. $seriesMap = TextbookSeries::query()
  82. ->pluck('name', 'id')
  83. ->toArray();
  84. }
  85. return $seriesMap[$seriesId] ?? '未归类系列';
  86. }
  87. }