From 7f1048352d09738ba6f4811ff84e6c4c2c9e4582 Mon Sep 17 00:00:00 2001 From: Franz Liedke Date: Tue, 9 Jul 2019 00:02:17 +0200 Subject: [PATCH] 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. --- src/Notification/NotificationRepository.php | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/Notification/NotificationRepository.php b/src/Notification/NotificationRepository.php index 9b0e608eb..1a6eefae1 100644 --- a/src/Notification/NotificationRepository.php +++ b/src/Notification/NotificationRepository.php @@ -13,6 +13,7 @@ namespace Flarum\Notification; use Carbon\Carbon; use Flarum\User\User; +use Illuminate\Database\Query\Expression; class NotificationRepository { @@ -26,10 +27,8 @@ class NotificationRepository */ public function findByUser(User $user, $limit = null, $offset = 0) { - $primaries = Notification::select( - app('flarum.db')->raw('MAX(id) AS id'), - app('flarum.db')->raw('SUM(read_at IS NULL) AS unread_count') - ) + $primaries = Notification::selectRaw('MAX(id) AS id') + ->selectRaw('SUM(read_at IS NULL) AS unread_count') ->where('user_id', $user->id) ->whereIn('type', $user->getAlertableNotificationTypes()) ->where('is_deleted', false) @@ -39,9 +38,11 @@ class NotificationRepository ->skip($offset) ->take($limit); - return Notification::select('notifications.*', app('flarum.db')->raw('p.unread_count')) - ->mergeBindings($primaries->getQuery()) - ->join(app('flarum.db')->raw('('.$primaries->toSql().') p'), 'notifications.id', '=', app('flarum.db')->raw('p.id')) + return Notification::select('notifications.*') + ->selectRaw('p.unread_count') + // 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() ->get(); }