Closed
Description
- Laravel Version: 5.4.28
- PHP Version: 7.1.4
- Database Driver & Version: MySQL 5.7.17
Description:
When the foreign key of a relation is null
, then don't execute the SQL call when trying to load the relation.
Steps To Reproduce:
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’t 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
.
Metadata
Metadata
Assignees
Labels
No labels