Skip to content

Commit

Permalink
fallback to primary key if owner key doesnt exist on model at all
Browse files Browse the repository at this point in the history
  • Loading branch information
taylorotwell committed Apr 22, 2021
1 parent a9be6f5 commit a011109
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
8 changes: 7 additions & 1 deletion src/Illuminate/Database/Eloquent/Relations/MorphTo.php
Expand Up @@ -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(
Expand Down
6 changes: 3 additions & 3 deletions tests/Database/DatabaseEloquentMorphToTest.php
Expand Up @@ -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');
Expand Down

0 comments on commit a011109

Please sign in to comment.