Skip to content

Eager Loading Notification Categories #280

@gaussian1

Description

@gaussian1

Problem:
On Retrieving Notifications an N+1 query problem occurs for notification categories

Here are the SQL Queries after running:

$notifications = Auth::user()->getNotifications(4);
foreach ($notifications as $notification) {
  echo $notification->text;
}

notifynder

Analysis:
On attempting to eager load, the following function is called inside the NotificationParser that forces one query per category

/** src/Notifynder/Parsers/NotificationParser@parse */
public function parse($notification, $categoryId)
{
  $category = NotificationCategory::findOrFail($categoryId);
  //...
}

Possible Solution:
I can create a pull request that checks whether the passed Notification's category relation is eager loaded, to be something like

/** src/Notifynder/Parsers/NotificationParser@parse */
public function parse($notification, $categoryId)
{ 
  $category = $notification->relationLoaded('category') ? $notification->category : NotificationCategory::findOrFail($categoryId);
  //...
}

If the above solution is okay, I can easily add the pull request, Cheers!


Notes:
The relationLoaded function was added in a later version of Laravel, I guess it was 5.1 but I am not sure, if we decide not to use it we can add a function to the Notification Model

/** src/Notifynder/Models/Notification
 *
 * Determine if we've already loaded the category
 *
 * @return bool
 */
 public function isCategoryLoaded() {
   return isset($this->relations['category']);
 }

Environment:
Laravel Framework 5.4.27
Notifynder 4.2.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions