News.php 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. protected function newsImgPcUrl(): Attribute
  28. {
  29. return Attribute::make(
  30. get: fn ($value) => is_null($this->news_img_pc) ? null :Storage::disk('public')->url($this->news_img_pc),
  31. );
  32. }
  33. protected function newsImgMobileUrl(): Attribute
  34. {
  35. return Attribute::make(
  36. get: fn ($value) => is_null($this->news_img_mobile) ? null :Storage::disk('public')->url($this->news_img_mobile),
  37. );
  38. }
  39. protected function newsMetaImg(): Attribute
  40. {
  41. return Attribute::make(
  42. get: fn ($value) => is_null($this->meta_img) ? null :Storage::disk('public')->url($this->meta_img),
  43. );
  44. }
  45. protected function listAuditState(): Attribute
  46. {
  47. return Attribute::make(
  48. get: fn ($value) => $this->attributes["visible"] == 1 ? "已發佈" : "暫存",
  49. );
  50. }
  51. protected static function booted()
  52. {
  53. static::saving(function ($news) {
  54. // 如果正在將此記錄設為置頂
  55. if ($news->isDirty('on_top') && $news->on_top == 1) {
  56. // 將其他所有記錄的置頂狀態取消
  57. static::where('id', '!=', $news->id)
  58. ->where('news_category_id', $news->news_category_id)
  59. ->where('on_top', 1)
  60. ->update(['on_top' => 0]);
  61. }
  62. });
  63. }
  64. }