diff --git a/src/Illuminate/Database/Eloquent/Relations/MorphOneOrMany.php b/src/Illuminate/Database/Eloquent/Relations/MorphOneOrMany.php index 58de31c29ae6..03a776bf048e 100755 --- a/src/Illuminate/Database/Eloquent/Relations/MorphOneOrMany.php +++ b/src/Illuminate/Database/Eloquent/Relations/MorphOneOrMany.php @@ -91,7 +91,7 @@ protected function setForeignAttributesForCreate(Model $model) public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) { return parent::getRelationExistenceQuery($query, $parentQuery, $columns)->where( - $this->morphType, $this->morphClass + $query->qualifyColumn($this->getMorphType()), $this->morphClass ); } diff --git a/tests/Integration/Database/EloquentMorphManyTest.php b/tests/Integration/Database/EloquentMorphManyTest.php index 959bee211fad..6966b9b18155 100644 --- a/tests/Integration/Database/EloquentMorphManyTest.php +++ b/tests/Integration/Database/EloquentMorphManyTest.php @@ -43,6 +43,19 @@ public function test_update_model_with_default_withCount() $this->assertEquals('new name', $post->title); } + + public function test_self_referencing_existence_query() + { + $post = Post::create(['title' => 'foo']); + + $comment = tap((new Comment(['name' => 'foo']))->commentable()->associate($post))->save(); + + (new Comment(['name' => 'bar']))->commentable()->associate($comment)->save(); + + $comments = Comment::has('replies')->get(); + + $this->assertEquals([1], $comments->pluck('id')->all()); + } } class Post extends Model @@ -68,4 +81,9 @@ public function commentable() { return $this->morphTo(); } + + public function replies() + { + return $this->morphMany(self::class, 'commentable'); + } }