Skip to content

Commit 42b71be

Browse files
committed
Merge pull request #5984 from JosephSilber/direct-morphs
[4.2] Set morphs directly
2 parents e29253c + 669c535 commit 42b71be

File tree

2 files changed

+12
-13
lines changed

2 files changed

+12
-13
lines changed

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

+8-11
Original file line numberDiff line numberDiff line change
@@ -101,32 +101,29 @@ public function save(Model $model)
101101
*/
102102
public function create(array $attributes)
103103
{
104-
$foreign = $this->getForeignAttributesForCreate();
104+
$instance = $this->related->newInstance($attributes);
105105

106106
// When saving a polymorphic relationship, we need to set not only the foreign
107107
// key, but also the foreign key type, which is typically the class name of
108108
// the parent model. This makes the polymorphic item unique in the table.
109-
$attributes = array_merge($attributes, $foreign);
110-
111-
$instance = $this->related->newInstance($attributes);
109+
$this->setForeignAttributesForCreate($instance);
112110

113111
$instance->save();
114112

115113
return $instance;
116114
}
117115

118116
/**
119-
* Get the foreign ID and type for creating a related model.
117+
* Set the foreign ID and type for creating a related model.
120118
*
121-
* @return array
119+
* @param \Illuminate\Database\Eloquent\Model $model
120+
* @return void
122121
*/
123-
protected function getForeignAttributesForCreate()
122+
protected function setForeignAttributesForCreate(Model $model)
124123
{
125-
$foreign = array($this->getPlainForeignKey() => $this->getParentKey());
126-
127-
$foreign[last(explode('.', $this->morphType))] = $this->morphClass;
124+
$model->{$this->getPlainForeignKey()} = $this->getParentKey();
128125

129-
return $foreign;
126+
$model->{last(explode('.', $this->morphType))} = $this->morphClass;
130127
}
131128

132129
/**

tests/Database/DatabaseEloquentMorphTest.php

+4-2
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,10 @@ public function testCreateFunctionOnMorph()
6060
{
6161
// Doesn't matter which relation type we use since they share the code...
6262
$relation = $this->getOneRelation();
63-
$created = m::mock('stdClass');
64-
$relation->getRelated()->shouldReceive('newInstance')->once()->with(array('name' => 'taylor', 'morph_id' => 1, 'morph_type' => get_class($relation->getParent())))->andReturn($created);
63+
$created = m::mock('Illuminate\Database\Eloquent\Model');
64+
$created->shouldReceive('setAttribute')->once()->with('morph_id', 1);
65+
$created->shouldReceive('setAttribute')->once()->with('morph_type', get_class($relation->getParent()));
66+
$relation->getRelated()->shouldReceive('newInstance')->once()->with(array('name' => 'taylor'))->andReturn($created);
6567
$created->shouldReceive('save')->once()->andReturn(true);
6668

6769
$this->assertEquals($created, $relation->create(array('name' => 'taylor')));

0 commit comments

Comments
 (0)