fix: videos/workshops query optmization

This commit is contained in:
Xavier Oliveira
2026-06-02 15:50:47 +01:00
parent bcaff422a0
commit c5ed77945e
8 changed files with 133 additions and 209 deletions

View File

@@ -70,7 +70,6 @@ class AuthController extends Controller
"name" => $user->name,
"email" => $user->email,
"role_id" => $user->role_id,
"password" => $user->password,
"created_at" => $user->created_at,
],
]);
@@ -104,20 +103,28 @@ class AuthController extends Controller
public function me()
{
$user = auth()->user();
$videosWatched = Video::select('id')
->with('views')
->whereHas('views', function ($q) use ($user) {
$q->where('user_id', $user->id);
})->count();
$videosCount = Video::select('id')->where('is_active', true)->count();
$userId = $user->id;
$role = $user->role_id;
if ($role !== 1) {
$stats = Video::selectRaw('
COUNT(CASE WHEN is_active = 1 THEN 1 END) as active_count,
COUNT(CASE WHEN is_active = 1 AND EXISTS (
SELECT 1 FROM video_views
WHERE video_views.video_id = videos.id
AND video_views.user_id = ?
) THEN 1 END) as watched_count
', [$userId])
->first();
}
return response()->json([
'message' => 'Utilizador obtido com sucesso',
'data' => [
'id' => $user->id,
'role_id' => $user->role_id,
'videosWatched' => $videosWatched,
'videosCount' => $videosCount,
'videosWatched' => $stats->watched_count ?? 0,
'videosCount' => $stats->active_count ?? 0,
],
'errors' => null,
], 200);