Skip to content

Optimize eager loading when no keys to be loaded #43689

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

Closed

Conversation

garygreen
Copy link
Contributor

@garygreen garygreen commented Aug 12, 2022

Currently when eager loading relations that don't have any keys to be loaded Laravel will still execute the query:

Example:

class User {
   public function picture()
   {
      return $this->belongsTo(Picture::class);
   }
}

User::create(['picture_id' => null]),
User::create(['picture_id' => null])
$users = User::all()->load(['picture']);

The eager load will trigger a select on the database even though there is no model keys to be loaded.

It does this by replacing replacing the empty where in (...) with where 0 = 1:

select * from `pictures` where 0 = 1

This PR checks to see if there are not any model keys that can be loaded, and if so will implicitly return an empty collection - this prevents the unnecessary database query.

@taylorotwell
Copy link
Member

Thanks for your pull request to Laravel!

Unfortunately, I'm going to delay merging this code for now. To preserve our ability to adequately maintain the framework, we need to be very careful regarding the amount of code we include.

If possible, please consider releasing your code as a package so that the community can still take advantage of your contributions!

If you feel absolutely certain that this code corrects a bug in the framework, please "@" mention me in a follow-up comment with further explanation so that GitHub will send me a notification of your response.

@garygreen
Copy link
Contributor Author

@taylorotwell Please could you elaborate more on why this wasn't accepted? In our app we have hundreds of impossible where calls to mysql due to this. It's an optimization that removes unnecessary calls to the database...

Would you be willing to accept a PR that at least makes it easier to add this as a custom package?

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

Successfully merging this pull request may close these issues.

2 participants