When the foreign key of a relation is null, then don't execute the SQL call when trying to load the relation.
Assume the following Eloquent model that has an (optional) relationship (i.e. the author_id field is nullable):
class Post extends Model {
/**
* Relation to (optional) author model
*/
public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'author_id');
}
...
}
If $post->author_id === null, then that post doesn鈥檛 have an author (duh!).
However, when I reference the relation with $post->author or $post->load('author'), then Laravel 5.4 is still tries to query the database. Using debugbar, I see:
select * from `users` where `users`.`user_id` in ('') and `users`.`deleted_at` is null
It seems to me that all the relation logic that gets executed -- and especially the SQL call -- could be skipped if the foreign key to a relation is null, no? Basically, if author_id is null, then just return null.
Makes sense
Sorry if I misunderstood the issue, but what if the null value in itself is an id (despite how bad this practice)? In that case, the returned value is the expected one.
For suggestions and feature requests please use the https://github.com/laravel/internals repo.
Will do, @themsaid. I did ask in the internals channel on slack whether this is a bug or new proposal, and it was suggested I post here. Sorry!
I'll repost over on the other repo.
Had this today myself, https://github.com/laravel/ideas/issues/748#issuecomment-372791896 said that this should be considered a bug, not a feature, but this hasn't been reopened yet (and the duplicate has been closed). Would be nice to have this "fixed"!
+1
Most helpful comment
Had this today myself, https://github.com/laravel/ideas/issues/748#issuecomment-372791896 said that this should be considered a bug, not a feature, but this hasn't been reopened yet (and the duplicate has been closed). Would be nice to have this "fixed"!