Framework: Eloquent doesn't need to execute relation query if foreign key is null

Created on 17 Aug 2017  路  6Comments  路  Source: laravel/framework

  • 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鈥檛 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.

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"!

All 6 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lzp819739483 picture lzp819739483  路  3Comments

gabriellimo picture gabriellimo  路  3Comments

RomainSauvaire picture RomainSauvaire  路  3Comments

ghost picture ghost  路  3Comments

PhiloNL picture PhiloNL  路  3Comments