News.php 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Casts\Attribute;
  4. use Illuminate\Database\Eloquent\Factories\HasFactory;
  5. use Illuminate\Database\Eloquent\Model;
  6. use Illuminate\Database\Eloquent\SoftDeletes;
  7. use Illuminate\Support\Facades\Storage;
  8. use RalphJSmit\Laravel\SEO\Support\HasSEO;
  9. use App\Models\NewsCategory;
  10. use Spatie\Translatable\HasTranslations;
  11. class News extends Model
  12. {
  13. use HasFactory, SoftDeletes, HasTranslations;
  14. protected $casts = [
  15. 'on_top' => 'boolean',
  16. "list_audit_state" => "string",
  17. ];
  18. protected $guarded = ['id'];
  19. protected $appends = ["news_img_pc_url", "news_img_mobile_url", "news_meta_img"];
  20. public $translatable = ['title', 'written_by', 'description', 'meta_title', 'meta_description', 'meta_keyword'];
  21. public function newsCategory(){
  22. return $this->belongsTo(NewsCategory::class);
  23. }
  24. public function paragraphs(){
  25. return $this->hasMany(NewsParagraph::class)->orderBy('order');
  26. }
  27. public function photos(){
  28. return $this->hasMany(NewsPhoto::class)->orderBy("order");
  29. }
  30. protected function newsImgPcUrl(): Attribute
  31. {
  32. return Attribute::make(
  33. get: fn ($value) => is_null($this->news_img_pc) ? null :Storage::disk('public')->url($this->news_img_pc),
  34. );
  35. }
  36. protected function newsImgMobileUrl(): Attribute
  37. {
  38. return Attribute::make(
  39. get: fn ($value) => is_null($this->news_img_mobile) ? null :Storage::disk('public')->url($this->news_img_mobile),
  40. );
  41. }
  42. protected function newsMetaImg(): Attribute
  43. {
  44. return Attribute::make(
  45. get: fn ($value) => is_null($this->meta_img) ? null :Storage::disk('public')->url($this->meta_img),
  46. );
  47. }
  48. protected function listAuditState(): Attribute
  49. {
  50. return Attribute::make(
  51. get: fn ($value) => $this->attributes["visible"] == 1 ? "已發佈" : "暫存",
  52. );
  53. }
  54. protected static function booted()
  55. {
  56. static::saving(function ($news) {
  57. // 如果正在將此記錄設為置頂
  58. if ($news->isDirty('on_top') && $news->on_top == 1) {
  59. // 將其他所有記錄的置頂狀態取消
  60. static::where('id', '!=', $news->id)
  61. ->where('news_category_id', $news->news_category_id)
  62. ->where('on_top', 1)
  63. ->update(['on_top' => 0]);
  64. }
  65. });
  66. }
  67. }