NewsParagraph.php 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Spatie\Translatable\HasTranslations;
  5. class NewsParagraph extends Model
  6. {
  7. use HasTranslations;
  8. CONST IMAGE = 1;
  9. CONST TEXT = 2;
  10. protected $guarded = ['id'];
  11. public $timestamps = false;
  12. protected $casts = [
  13. 'text_content' => 'array', // JSON 轉陣列
  14. ];
  15. public function news(){
  16. return $this->belongsTo(News::class);
  17. }
  18. public function contentType()
  19. {
  20. switch ($this->paragraph_type){
  21. case 1:
  22. return "image";
  23. case 2:
  24. return "text";
  25. default:
  26. return "";
  27. }
  28. }
  29. public function photos(){
  30. return $this->hasMany(NewsParagraphPhoto::class)->orderBy("order");
  31. }
  32. /**
  33. * 取得特定語言的文字內容
  34. */
  35. public function getTextContent($locale = 'zh_TW'): string
  36. {
  37. if ($this->paragraph_type != 2) {
  38. return '';
  39. }
  40. $content = $this->text_content;
  41. if (is_array($content)) {
  42. return $content[$locale] ?? '';
  43. }
  44. if (is_string($content)) {
  45. $decoded = json_decode($content, true);
  46. return $decoded[$locale] ?? '';
  47. }
  48. return '';
  49. }
  50. }