| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- <?php
-
- namespace App\Models;
-
- use Illuminate\Database\Eloquent\Casts\Attribute;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Database\Eloquent\SoftDeletes;
- use Illuminate\Support\Facades\Storage;
- use Spatie\Translatable\HasTranslations;
-
- class News extends Model
- {
- use HasTranslations, SoftDeletes;
- protected $casts = [
- 'on_top' => 'boolean',
- "list_audit_state" => "string",
- ];
- protected $guarded = ['id'];
- protected $appends = ["news_img_url", "meta_img_url"];
- public $translatable = ['title', 'written_by', 'description', 'meta_title', 'meta_description', 'meta_keyword'];
-
- public function newsCategory(){
- return $this->belongsTo(NewsCategory::class);
- }
-
- public function paragraphs(){
- return $this->hasMany(NewsParagraph::class)->orderBy('order');
- }
- protected function newsImgUrl(): Attribute
- {
- return Attribute::make(
- get: fn ($value) => is_null($this->news_imgc) ? null :Storage::url($this->news_img),
- );
- }
-
- protected function metaImgUrl(): Attribute
- {
- return Attribute::make(
- get: fn ($value) => is_null($this->meta_img) ? null :Storage::url($this->meta_img),
- );
- }
-
- protected function listAuditState(): Attribute
- {
- return Attribute::make(
- get: fn ($value) => $this->attributes["visible"] == 1 ? "已發佈" : "暫存",
- );
- }
- protected static function booted()
- {
- static::saving(function ($news) {
- // 如果正在將此記錄設為置頂
- if ($news->isDirty('on_top') && $news->on_top == 1) {
- // 將其他所有記錄的置頂狀態取消
- static::where('id', '!=', $news->id)
- ->where('news_category_id', $news->news_category_id)
- ->where('on_top', 1)
- ->update(['on_top' => 0]);
- }
- });
- }
- }
|