Skip to content

Commit 3752934

Browse files
committed
Refactor query
1 parent 0d32d0f commit 3752934

File tree

1 file changed

+18
-13
lines changed

1 file changed

+18
-13
lines changed

app/Models/User.php

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
use Illuminate\Database\Eloquent\Factories\HasFactory;
1212
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
1313
use Illuminate\Database\Eloquent\Relations\HasMany;
14+
use Illuminate\Database\Query\JoinClause;
1415
use Illuminate\Foundation\Auth\User as Authenticatable;
1516
use Illuminate\Notifications\Notifiable;
1617
use Illuminate\Support\Facades\Auth;
@@ -340,19 +341,23 @@ public function countSolutions(): int
340341

341342
public function scopeMostSolutions(Builder $query, ?int $inLastDays = null)
342343
{
343-
return $query->withCount(['replyAble as solutions_count' => function ($query) use ($inLastDays) {
344-
$query->where('replyable_type', 'threads')
345-
->join('threads', function ($join) {
346-
$join->on('threads.solution_reply_id', '=', 'replies.id')
347-
->on('threads.author_id', '!=', 'replies.author_id');
348-
});
349-
350-
if ($inLastDays) {
351-
$query->where('replies.created_at', '>', now()->subDays($inLastDays));
352-
}
353-
354-
return $query;
355-
}])
344+
return $query
345+
->selectRaw('users.*, COUNT(DISTINCT replies.id) AS solutions_count')
346+
->join('replies', 'replies.author_id', '=', 'users.id')
347+
->join('threads', function (JoinClause $join) {
348+
$join->on('threads.solution_reply_id', '=', 'replies.id')
349+
->on('threads.author_id', '!=', 'replies.author_id');
350+
})
351+
->where(function ($query) use ($inLastDays) {
352+
$query->where('replyable_type', 'threads');
353+
354+
if ($inLastDays) {
355+
$query->where('replies.created_at', '>', now()->subDays($inLastDays));
356+
}
357+
358+
return $query;
359+
})
360+
->groupBy('users.id')
356361
->having('solutions_count', '>', 0)
357362
->orderBy('solutions_count', 'desc');
358363
}

0 commit comments

Comments
 (0)