Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.6] Fix MorphTo lazy eager loading #25240

Merged
merged 1 commit into from
Aug 17, 2018
Merged

[5.6] Fix MorphTo lazy eager loading #25240

merged 1 commit into from
Aug 17, 2018

Conversation

staudenmeir
Copy link
Contributor

@staudenmeir staudenmeir commented Aug 17, 2018

Collection::load() uses the first model to get the relationships for lazy eager loading. This can cause problems on MorphTo relationships when the related models differ in certain aspects:

Example 1: Different relationships in $with (#16604)

class Comment extends Model {
    public function commentable() {
        return $this->morphTo();
    }
}

class Post extends Model {
    protected $with = ['user'];

    public function user() {
        return $this->belongsTo(User::class);
    }
}

class Video extends Model {}

$post = Post::create(['user_id' => 1]);
$video = Video::create();
(new Comment)->commentable()->associate($post)->save();
(new Comment)->commentable()->associate($video)->save();

Comment::all()->load('commentable');

This fails because Eloquent tries to load the user relationship on $video (as specified in $post).

Example 2: Different primary keys (#24654)

class Comment extends Model {
    public function commentable() {
        return $this->morphTo();
    }
}

class Post extends Model {
    protected $primaryKey = 'post_id';
}

class Video extends Model {
    protected $primaryKey = 'video_id';
}

$post = Post::create();
$video = Video::create();
(new Comment)->commentable()->associate($post)->save();
(new Comment)->commentable()->associate($video)->save();

Comment::all()->load('commentable');

This fails because Eloquent tries to access the videos.post_id column (as specified in $post).


All this is caused by HasRelationships::morphTo() only calling morphEagerTo() on eager loading: On lazy eager loading, morphInstanceTo() is used.

We can fix the problem by always using a fresh model instance when getting the relationship in Builder::getRelation(). This mimics eager loading where the query builder is initialized with a fresh instance.

The new integration test combines different primary keys and the usage of $with.

Fixes #16604 and fixes #24654.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants