diff --git a/src/Illuminate/Database/Eloquent/Relations/MorphTo.php b/src/Illuminate/Database/Eloquent/Relations/MorphTo.php index 53d25cb4470a..262741f30cfb 100644 --- a/src/Illuminate/Database/Eloquent/Relations/MorphTo.php +++ b/src/Illuminate/Database/Eloquent/Relations/MorphTo.php @@ -231,8 +231,14 @@ protected function matchToMorphParents($type, Collection $results) */ public function associate($model) { + if ($model instanceof Model) { + $foreignKey = $this->ownerKey && $model->{$this->ownerKey} + ? $this->ownerKey + : $model->getKeyName(); + } + $this->parent->setAttribute( - $this->foreignKey, $model instanceof Model ? $model->{$this->ownerKey ?: $model->getKeyName()} : null + $this->foreignKey, $model instanceof Model ? $model->{$foreignKey} : null ); $this->parent->setAttribute( diff --git a/tests/Database/DatabaseEloquentMorphToTest.php b/tests/Database/DatabaseEloquentMorphToTest.php index 6895d3a656de..a2046c8e5f2f 100644 --- a/tests/Database/DatabaseEloquentMorphToTest.php +++ b/tests/Database/DatabaseEloquentMorphToTest.php @@ -134,13 +134,13 @@ public function testMorphToWithSpecifiedClassDefault() public function testAssociateMethodSetsForeignKeyAndTypeOnModel() { $parent = m::mock(Model::class); - $parent->shouldReceive('getAttribute')->once()->with('foreign_key')->andReturn('foreign.value'); + $parent->shouldReceive('getAttribute')->with('foreign_key')->andReturn('foreign.value'); $relation = $this->getRelationAssociate($parent); $associate = m::mock(Model::class); - $associate->shouldReceive('getAttribute')->once()->andReturn(1); - $associate->shouldReceive('getMorphClass')->once()->andReturn('Model'); + $associate->shouldReceive('getAttribute')->andReturn(1); + $associate->shouldReceive('getMorphClass')->andReturn('Model'); $parent->shouldReceive('setAttribute')->once()->with('foreign_key', 1); $parent->shouldReceive('setAttribute')->once()->with('morph_type', 'Model');