fulinqingjie/app/Models/Article.php

75 lines
1.8 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use EloquentFilter\Filterable;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class Article extends Model
{
use HasFactory;
use Filterable;
protected function serializeDate(\DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
protected $appends = ['tags', 'cover_url'];
protected $casts = [
'created_at' => 'datetime:Y-m-d H:i:s',
'updated_at' => 'datetime:Y-m-d H:i:s',
'published_at' => 'datetime:Y-m-d H:i:s',
'is_enable' => 'boolean',
'is_recommend' => 'boolean',
'appendixes' => 'array',
];
protected $fillable = [
'title',
'content',
'cover',
'category',
't_ids',
'published_at',
'is_enable',
'is_recommend',
'sort',
'appendixes',
];
protected function coverUrl():Attribute {
return Attribute::make(
get: fn($value) => $this->cover ? (Str::startsWith($this->cover, ['http://', 'https://']) ? $this->cover : Storage::url($this->cover)) : null,
);
}
public function scopeRecommend($q){
$q->where('is_recommend', true);
}
public function scopeShow($q){
$q->where('is_enable', true)->where('published_at', '<=', now());
}
public function scopeSort($q)
{
$q->orderBy('is_recommend', 'desc')
->orderBy('sort', 'asc')
->orderBy('published_at', 'desc')
->orderBy('created_at', 'desc');
}
protected function tags():Attribute
{
return Attribute::make(
get: fn($value) => $this->t_ids ? explode(',', $this->t_ids) : [],
);
}
}