Skip to content

Commit a011109

Browse files
committed
fallback to primary key if owner key doesnt exist on model at all
1 parent a9be6f5 commit a011109

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

src/Illuminate/Database/Eloquent/Relations/MorphTo.php

+7-1
Original file line numberDiff line numberDiff line change
@@ -231,8 +231,14 @@ protected function matchToMorphParents($type, Collection $results)
231231
*/
232232
public function associate($model)
233233
{
234+
if ($model instanceof Model) {
235+
$foreignKey = $this->ownerKey && $model->{$this->ownerKey}
236+
? $this->ownerKey
237+
: $model->getKeyName();
238+
}
239+
234240
$this->parent->setAttribute(
235-
$this->foreignKey, $model instanceof Model ? $model->{$this->ownerKey ?: $model->getKeyName()} : null
241+
$this->foreignKey, $model instanceof Model ? $model->{$foreignKey} : null
236242
);
237243

238244
$this->parent->setAttribute(

tests/Database/DatabaseEloquentMorphToTest.php

+3-3
Original file line numberDiff line numberDiff line change
@@ -134,13 +134,13 @@ public function testMorphToWithSpecifiedClassDefault()
134134
public function testAssociateMethodSetsForeignKeyAndTypeOnModel()
135135
{
136136
$parent = m::mock(Model::class);
137-
$parent->shouldReceive('getAttribute')->once()->with('foreign_key')->andReturn('foreign.value');
137+
$parent->shouldReceive('getAttribute')->with('foreign_key')->andReturn('foreign.value');
138138

139139
$relation = $this->getRelationAssociate($parent);
140140

141141
$associate = m::mock(Model::class);
142-
$associate->shouldReceive('getAttribute')->once()->andReturn(1);
143-
$associate->shouldReceive('getMorphClass')->once()->andReturn('Model');
142+
$associate->shouldReceive('getAttribute')->andReturn(1);
143+
$associate->shouldReceive('getMorphClass')->andReturn('Model');
144144

145145
$parent->shouldReceive('setAttribute')->once()->with('foreign_key', 1);
146146
$parent->shouldReceive('setAttribute')->once()->with('morph_type', 'Model');

0 commit comments

Comments
 (0)