laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Warn if relation's foreign key is not in select list #2550

Closed shaedrich closed 3 years ago

shaedrich commented 3 years ago

If I have something like this

class Post extends Model
{
    public function comments(): HasMany
    {
        return $this->hasMany(Comment::class)->select('body');
    }
}

class Comment extends Model
{
    public function attachments(): HasMany
    {
        return $this->hasMany(Attachment::class);
    }
}

Comment just has an empty attachments array. I know, why this happens and that I can solve this, by adding 'id' to the 'select()` method call, but wouldn't it be good if Eloquent knew that it needs this key? Since there's no error message, the mistake is everything but obvious due to the abstraction Laravel and Eloquent have.

themsaid commented 3 years ago

Feel free to submit a PR with your suggested changes.