diff --git a/phpcs.xml.dist b/phpcs.xml.dist index d7dd1e724..3b7cc671c 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -49,4 +49,8 @@ docs/**/*.php + + + tests/Ticket/*.php + diff --git a/src/Eloquent/HybridRelations.php b/src/Eloquent/HybridRelations.php index 5c058f50f..be20327ee 100644 --- a/src/Eloquent/HybridRelations.php +++ b/src/Eloquent/HybridRelations.php @@ -226,7 +226,7 @@ public function morphTo($name = null, $type = null, $id = null, $ownerKey = null $this->newQuery(), $this, $id, - $ownerKey ?: $this->getKeyName(), + $ownerKey, $type, $name, ); diff --git a/src/Relations/MorphTo.php b/src/Relations/MorphTo.php index 1eff5e53b..692991372 100644 --- a/src/Relations/MorphTo.php +++ b/src/Relations/MorphTo.php @@ -17,7 +17,7 @@ public function addConstraints() // or has many relationships, we need to actually query on the primary key // of the related models matching on the foreign key that's on a parent. $this->query->where( - $this->ownerKey, + $this->ownerKey ?? $this->getForeignKeyName(), '=', $this->getForeignKeyFrom($this->parent), ); diff --git a/tests/Ticket/GH2783Test.php b/tests/Ticket/GH2783Test.php new file mode 100644 index 000000000..73324ddc0 --- /dev/null +++ b/tests/Ticket/GH2783Test.php @@ -0,0 +1,75 @@ + 'Lorem ipsum']); + $user = GH2783User::create(['username' => 'jsmith']); + + $imageWithPost = GH2783Image::create(['uri' => 'http://example.com/post.png']); + $imageWithPost->imageable()->associate($post)->save(); + + $imageWithUser = GH2783Image::create(['uri' => 'http://example.com/user.png']); + $imageWithUser->imageable()->associate($user)->save(); + + $queriedImageWithPost = GH2783Image::with('imageable')->find($imageWithPost->getKey()); + $this->assertInstanceOf(GH2783Post::class, $queriedImageWithPost->imageable); + $this->assertEquals($post->_id, $queriedImageWithPost->imageable->getKey()); + + $queriedImageWithUser = GH2783Image::with('imageable')->find($imageWithUser->getKey()); + $this->assertInstanceOf(GH2783User::class, $queriedImageWithUser->imageable); + $this->assertEquals($user->username, $queriedImageWithUser->imageable->getKey()); + } +} + +class GH2783Image extends Model +{ + protected $connection = 'mongodb'; + protected $fillable = ['uri']; + + public function imageable(): MorphTo + { + return $this->morphTo(__FUNCTION__, 'imageable_type', 'imageable_id'); + } +} + +class GH2783Post extends Model +{ + protected $connection = 'mongodb'; + protected $fillable = ['text']; + + public function image(): MorphOne + { + return $this->morphOne(GH2783Image::class, 'imageable'); + } +} + +class GH2783User extends Model +{ + protected $connection = 'mongodb'; + protected $fillable = ['username']; + protected $primaryKey = 'username'; + + public function image(): MorphOne + { + return $this->morphOne(GH2783Image::class, 'imageable'); + } +}