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 2697397376
commit 928b360135

View File

@ -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();
}