123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Casts\Attribute;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Database\Eloquent\SoftDeletes;
  6. use Illuminate\Support\Facades\Storage;
  7. use Spatie\Translatable\HasTranslations;
  8. class Project extends Model
  9. {
  10. use HasTranslations, SoftDeletes;
  11. protected $guarded = ['id'];
  12. protected $translatable = ["name", "sub_name", "summaries", "img_alt", "address", "floor_plan",
  13. "building_structure", "design_unit", "contact_unit", "contact_phone", "inversment_phone"
  14. ];
  15. protected $casts = ["img_url" => "array"];
  16. protected $appends = ["first_list_img_url", "img_list", "meta_img_url"];
  17. public function region()
  18. {
  19. return $this->belongsTo(Region::class);
  20. }
  21. public function tags()
  22. {
  23. return $this->morphToMany(Tag::class, 'taggable');
  24. }
  25. public function badges()
  26. {
  27. return $this->morphToMany(Badge::class, 'badgeable');
  28. }
  29. public function histories()
  30. {
  31. return $this->hasMany(ProjectHistory::class);
  32. }
  33. public function spaceInfos()
  34. {
  35. return $this->hasMany(ProjectSpaceInfo::class);
  36. }
  37. protected function metaImgUrl(): Attribute
  38. {
  39. return Attribute::make(
  40. get: fn ($value) => is_null($this->meta_img) ? null :Storage::url($this->meta_img),
  41. );
  42. }
  43. public function firstListImgUrl(): Attribute
  44. {
  45. return Attribute::make(
  46. get: fn ($value) => is_null($this->img_url) ? null :Storage::url($this->img_url[0]),
  47. );
  48. }
  49. public function imgList(): Attribute
  50. {
  51. $imgList = [];
  52. if(!is_null($this->img_url) && count($this->img_url) > 0){
  53. foreach($this->img_url as $img){
  54. $imgList[] = Storage::url($img);
  55. }
  56. }
  57. return Attribute::make(
  58. get: fn ($value) => $imgList,
  59. );
  60. }
  61. public function getBadges($locale) : array
  62. {
  63. $badges = [];
  64. if($this->badges->count() > 0){
  65. foreach($this->badges as $badge){
  66. $badges[] = [
  67. "imgUrl" => $badge->imgUrlLink,
  68. "name" => $badge->getTranslation("name", $locale),
  69. "rewardYear" => "取得年份 : " . $badge->reward_year
  70. ];
  71. }
  72. }
  73. return $badges;
  74. }
  75. public function getTags($locale) : array
  76. {
  77. $tags = [];
  78. if($this->tags->count() > 0){
  79. foreach($this->tags as $tag){
  80. $tags[] = [
  81. "id" => $tag->id,
  82. "name" => $tag->getTranslation("name", $locale),
  83. ];
  84. }
  85. }
  86. return $tags;
  87. }
  88. }