| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- <?php
-
- namespace App\Models;
-
- use Illuminate\Database\Eloquent\Model;
- use Spatie\Translatable\HasTranslations;
-
- class NewsParagraph extends Model
- {
- use HasTranslations;
- CONST IMAGE = 1;
- CONST TEXT = 2;
-
- protected $guarded = ['id'];
- public $timestamps = false;
- protected $casts = [
- 'text_content' => 'array', // JSON 轉陣列
- ];
-
- public function news(){
- return $this->belongsTo(News::class);
- }
-
- public function contentType()
- {
- switch ($this->paragraph_type){
- case 1:
- return "image";
- case 2:
- return "text";
- default:
- return "";
- }
- }
- public function photos(){
- return $this->hasMany(NewsParagraphPhoto::class)->orderBy("order");
- }
- /**
- * 取得特定語言的文字內容
- */
- public function getTextContent($locale = 'zh_TW'): string
- {
- if ($this->paragraph_type != 2) {
- return '';
- }
-
- $content = $this->text_content;
-
- if (is_array($content)) {
- return $content[$locale] ?? '';
- }
-
- if (is_string($content)) {
- $decoded = json_decode($content, true);
- return $decoded[$locale] ?? '';
- }
- return '';
- }
- }
|