parsaaghayi-backend/app/Models/Blog/Post.php
2024-10-13 20:16:08 +03:30

100 lines
2.6 KiB
PHP

<?php
namespace App\Models\Blog;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\User;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'title',
'body',
'excerpt',
'slug',
'author_id',
'category_id',
'featured_image',
'views',
'likes',
'published_at',
];
// رابطه با نویسنده
public function author()
{
return $this->belongsTo(User::class, 'author_id');
}
// رابطه با دسته‌بندی
public function category()
{
return $this->belongsTo(Category::class);
}
// رابطه با تگ‌ها
public function tags()
{
return $this->belongsToMany(Tag::class)->withTimestamps();
}
// پست‌های مرتبط
public function relatedPosts()
{
return $this->belongsToMany(Post::class, 'related_posts', 'post_id', 'related_post_id')->withTimestamps();
}
// اسکوپ فیلتر
public function scopeFilter($query, $filters)
{
if (isset($filters['category'])) {
$query->whereHas('category', function ($q) use ($filters) {
$q->where('slug', $filters['category']);
});
}
if (isset($filters['tag'])) {
$query->whereHas('tags', function ($q) use ($filters) {
$q->where('slug', $filters['tag']);
});
}
if (isset($filters['search'])) {
$query->where(function ($q) use ($filters) {
$q->where('title', 'like', '%' . $filters['search'] . '%')
->orWhere('body', 'like', '%' . $filters['search'] . '%');
});
}
if (isset($filters['author'])) {
$query->whereHas('author', function ($q) use ($filters) {
$q->where('id', $filters['author']);
});
}
if (isset($filters['published'])) {
$query->whereNotNull('published_at');
}
return $query;
}
/**
* Scope برای اعمال مرتب‌سازی
*/
public function scopeSort($query, $sortField, $sortDirection = 'asc')
{
// بررسی اینکه فیلد مرتب‌سازی معتبر است یا خیر
$allowedSortFields = ['published_at', 'views', 'likes', 'title'];
if (in_array($sortField, $allowedSortFields)) {
$sortDirection = strtolower($sortDirection) === 'desc' ? 'desc' : 'asc';
$query->orderBy($sortField, $sortDirection);
}
return $query;
}
}