aiblog/app/Services/SearchService.php
2024-11-17 11:30:01 +08:00

54 lines
No EOL
1.9 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services;
use App\Models\Post;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
class SearchService
{
protected CacheService $cacheService;
public function __construct(CacheService $cacheService)
{
$this->cacheService = $cacheService;
}
public function searchPosts(string $query, array $filters = [], int $perPage = 10): LengthAwarePaginator
{
return $this->cacheService
->tags(['search', 'posts'])
->remember("posts:search:{$query}", function () use ($query, $filters, $perPage) {
return Post::with(['author:id,name', 'category:id,name'])
->where(function ($q) use ($query) {
$q->where('title', 'like', "%{$query}%")
->orWhere('content', 'like', "%{$query}%")
->orWhere('summary', 'like', "%{$query}%");
})
->when(!empty($filters['category_id']), function ($q) use ($filters) {
$q->where('category_id', $filters['category_id']);
})
->when(!empty($filters['author_id']), function ($q) use ($filters) {
$q->where('author_id', $filters['author_id']);
})
->latest()
->paginate($perPage);
});
}
public function getRelatedPosts(Post $post, int $limit = 5): Collection
{
return $this->cacheService
->tags(['posts', 'related'])
->remember("posts:{$post->id}:related", function () use ($post, $limit) {
return Post::where('category_id', $post->category_id)
->where('id', '!=', $post->id)
->take($limit)
->latest()
->get();
});
}
}