News.php 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 News extends Model
  9. {
  10. use HasTranslations, SoftDeletes;
  11. protected $casts = [
  12. 'on_top' => 'boolean',
  13. "list_audit_state" => "string",
  14. ];
  15. protected $guarded = ['id'];
  16. protected $appends = ["news_img_url", "meta_img_url"];
  17. public $translatable = ['title', 'written_by', 'description', 'meta_title', 'meta_description', 'meta_keyword'];
  18. public function newsCategory(){
  19. return $this->belongsTo(NewsCategory::class);
  20. }
  21. public function paragraphs(){
  22. return $this->hasMany(NewsParagraph::class)->orderBy('order');
  23. }
  24. protected function newsImgUrl(): Attribute
  25. {
  26. return Attribute::make(
  27. get: fn ($value) => is_null($this->news_imgc) ? null :Storage::url($this->news_img),
  28. );
  29. }
  30. protected function metaImgUrl(): Attribute
  31. {
  32. return Attribute::make(
  33. get: fn ($value) => is_null($this->meta_img) ? null :Storage::url($this->meta_img),
  34. );
  35. }
  36. protected function listAuditState(): Attribute
  37. {
  38. return Attribute::make(
  39. get: fn ($value) => $this->attributes["visible"] == 1 ? "已發佈" : "暫存",
  40. );
  41. }
  42. protected static function booted()
  43. {
  44. static::saving(function ($news) {
  45. // 如果正在將此記錄設為置頂
  46. if ($news->isDirty('on_top') && $news->on_top == 1) {
  47. // 將其他所有記錄的置頂狀態取消
  48. static::where('id', '!=', $news->id)
  49. ->where('news_category_id', $news->news_category_id)
  50. ->where('on_top', 1)
  51. ->update(['on_top' => 0]);
  52. }
  53. });
  54. }
  55. }