Loading a BelongsTo relationship when the foreign key is null causes N+1 #43548
Replies: 2 comments 6 replies
-
According to laravel/ideas#748 this was resolved in Laravel 5.7 with #26992 . |
Beta Was this translation helpful? Give feedback.
2 replies
-
If I am reading this correctly, Certainly doesn't seem to be a null check in there. I guess there would have to be a null check, as with #748, followed by a call to getDefault, which somehow ties into the other models being loaded. |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I have a strange issue where calling
$model->load('relationship');
is running a query which will never return a value when that relationship's key is null.It seems that Laravel does not check whether a foreign key value is
null
prior to attempting an eager load, as per this issue on lazy loading: laravel/ideas#748I am running
beyondcode/laravel-query-detector
, and it flags it up as an N+1 issue every time.This feels like a bug, however I am uncertain whether this is something that is known and has a workaround.
Recreation
My setup for this is relatively simple, I have a model which has several optional relationships to another model.
Here is an abstracted example:
Post
Test
Laravel runs
select * from users where users.id in ('') and users.deleted_at is null
for eachnull
relationship, which not only gets flagged as an N+1 query but will never return anything.In my mind Laravel should not be attempting to load a null relationship.
Any thoughts?
Beta Was this translation helpful? Give feedback.
All reactions