Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More complex eager loading #3

Open
RyanPriceDotCa opened this issue Feb 21, 2018 · 0 comments
Open

More complex eager loading #3

RyanPriceDotCa opened this issue Feb 21, 2018 · 0 comments

Comments

@RyanPriceDotCa
Copy link

RyanPriceDotCa commented Feb 21, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant