Coding convention eager loading relationships

By @mratiebatie · 2021-09-07 12:03

Coding convention eager loading relationships

Hi!

I have a relational database for a Human Resource application. All employees are stored in the database and they have quite some relationships. On every page in the application different relationships have to be loaded for the employee. This results in a lot of unique eager loading relationships situations. I'm trying to separate my database calls in repositories so they won't end up in controllers.

Imagine having the following situation in 10 different controllers where every time the relations are slightly different:

public function getShifts() {
    return $employee->shifts()
        ->with([
            'employee',
            'employee.isPresent',
            'employee.tags',
            'employee.organization',
            'employee.timesheets',
            'employee.workhours',
            'department',
        ])
        ->get();
}

If I would abstract each eager load to a method in the repository, the repositories would still get really fat. Does anyone have a proper solution for this?

  • By @captbrogers · 2021-09-07 15:44

    My advice is that fat belongs somewhere and you can't always distribute it in an elegant way, especially when modifying an existing system. It may not be a bad thing to have some extra fat in the repository class or model class. Please understand that I'm not asking this to question your methods, but merely to understand the problem better: can you move some of the eager loading to the model and always include it? Relationships like employee tags, department, or isPresent all seem like simple enough data that it may be negligible on performance to list them in the 'with' array on the model if those relationships are on most of your other eager loading queries.

    • By @mratiebatie · 2021-09-13 12:01

      Thanks for your answer. I've considered this as well but since it's quite some data it would slow down page load. Also, some eager loading queries have a extra scope on a date field which I excluded for brevity.

      A couple of days ago I came up with the idea to start using ViewModels more. I think this is the best place to eager load extra data for a specific page. Thanks though!