Clean up database query

- Use existing `selectRaw()` method to avoid using the global `app()`
  helper as a service locator, which hides dependencies.
- Do the same for the join.
- The `Expression` is necessary to prevent the aliased column from being
  prefixed with the database table prefix, if configured.
This commit is contained in:
Franz Liedke 2019-07-09 00:02:17 +02:00
parent d2700961ba
commit 7f1048352d
No known key found for this signature in database
GPG Key ID: 9A0231A879B055F4

View File

@ -13,6 +13,7 @@ namespace Flarum\Notification;
use Carbon\Carbon; use Carbon\Carbon;
use Flarum\User\User; use Flarum\User\User;
use Illuminate\Database\Query\Expression;
class NotificationRepository class NotificationRepository
{ {
@ -26,10 +27,8 @@ class NotificationRepository
*/ */
public function findByUser(User $user, $limit = null, $offset = 0) public function findByUser(User $user, $limit = null, $offset = 0)
{ {
$primaries = Notification::select( $primaries = Notification::selectRaw('MAX(id) AS id')
app('flarum.db')->raw('MAX(id) AS id'), ->selectRaw('SUM(read_at IS NULL) AS unread_count')
app('flarum.db')->raw('SUM(read_at IS NULL) AS unread_count')
)
->where('user_id', $user->id) ->where('user_id', $user->id)
->whereIn('type', $user->getAlertableNotificationTypes()) ->whereIn('type', $user->getAlertableNotificationTypes())
->where('is_deleted', false) ->where('is_deleted', false)
@ -39,9 +38,11 @@ class NotificationRepository
->skip($offset) ->skip($offset)
->take($limit); ->take($limit);
return Notification::select('notifications.*', app('flarum.db')->raw('p.unread_count')) return Notification::select('notifications.*')
->mergeBindings($primaries->getQuery()) ->selectRaw('p.unread_count')
->join(app('flarum.db')->raw('('.$primaries->toSql().') p'), 'notifications.id', '=', app('flarum.db')->raw('p.id')) // Expression is necessary until Laravel 5.8.
// See https://github.com/laravel/framework/pull/28400
->joinSub($primaries, 'p', 'notifications.id', '=', new Expression('p.id'))
->latest() ->latest()
->get(); ->get();
} }