|
11 | 11 | use Illuminate\Database\Eloquent\Factories\HasFactory;
|
12 | 12 | use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
13 | 13 | use Illuminate\Database\Eloquent\Relations\HasMany;
|
| 14 | +use Illuminate\Database\Query\JoinClause; |
14 | 15 | use Illuminate\Foundation\Auth\User as Authenticatable;
|
15 | 16 | use Illuminate\Notifications\Notifiable;
|
16 | 17 | use Illuminate\Support\Facades\Auth;
|
@@ -340,19 +341,23 @@ public function countSolutions(): int
|
340 | 341 |
|
341 | 342 | public function scopeMostSolutions(Builder $query, ?int $inLastDays = null)
|
342 | 343 | {
|
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') |
356 | 361 | ->having('solutions_count', '>', 0)
|
357 | 362 | ->orderBy('solutions_count', 'desc');
|
358 | 363 | }
|
|
0 commit comments