Skip to content

More complex eager loading #3

Description

@RyanPriceDotCa

Hi Jonathan,

I "attended" your talk on eager loading in laravel at this year's online laracon. We're building our first app with laravel and it was very helpful as we are starting to see the same n+1 issues you were describing.

I'm struggling with a couple more advanced areas and I'm hoping you'd be willing to provide some guidance as I haven't been able to find much through my normal routine of googling.

I have two main questions.

  1. When you're constraining eager loads I am assuming when you access that eager loaded property later it will access the constrained version. For example, we have this snippet of code:

     // query every sent message
     $query = Message::sent()->whereIn('id', $msgIDs)->with(['sentTo' => function ($q) {
         $q->withTrashed();
     }]);
    

Before using the eager loading we would have accessed that property like this:

    $msg->sentTo()->withTrashed()->get()

but after we can just do:

    $msg->sentTo

and the framework will know that property was eager loaded and use what's there (which should be constrained to include the soft-deleted records) correct?

  1. A lot of our large query count is coming from custom attributes on our models. Is there a way to eager load those? For example, we have a model where we have a custom attribute (contact_name) that is generated based on the 'type' column in that same table. The code looks like this:
    public function getContactNameAttribute() {
        if ($this->type == "person") {
            $name = $this->user->full_name;
        } else {
            $name = $this->name;
        }
        return $name;
    }

So every time we're using the contact_name attribute it runs at least one query, and sometimes two if it needs to access the $this->user->full_name (User is another model).

Is there any way to eager load those custom attributes?

Again, appreciate the time you took putting the talk together - we found it really useful.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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