Skip to content

Commit 5d58b0f

Browse files
committed
add table name as default morph type
1 parent acb4b77 commit 5d58b0f

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -731,6 +731,10 @@ public function getMorphClass()
731731
return array_search(static::class, $morphMap, true);
732732
}
733733

734+
if (Relation::$tableNameAsMorphType) {
735+
return $this->getTable();
736+
}
737+
734738
return static::class;
735739
}
736740

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,13 @@ abstract class Relation
5555
*/
5656
public static $morphMap = [];
5757

58+
/**
59+
* Indicates if the morph relation type should default to table name.
60+
*
61+
* @var bool
62+
*/
63+
public static $tableNameAsMorphType = false;
64+
5865
/**
5966
* Create a new relation instance.
6067
*
@@ -341,6 +348,16 @@ public static function morphMap(array $map = null, $merge = true)
341348
return static::$morphMap;
342349
}
343350

351+
/**
352+
* Changes the default morph type to table name.
353+
*
354+
* @return void
355+
*/
356+
public static function tableNameAsMorphType()
357+
{
358+
self::$tableNameAsMorphType = true;
359+
}
360+
344361
/**
345362
* Builds a table-keyed array from model class names.
346363
*

tests/Database/DatabaseEloquentModelTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1200,6 +1200,23 @@ public function testCorrectMorphClassIsReturned()
12001200
}
12011201
}
12021202

1203+
public function testCorrectMorphClassIsReturnedOnChangingDefault()
1204+
{
1205+
Relation::tableNameAsMorphType();
1206+
Relation::morphMap(['alias' => EloquentModelCamelStub::class]);
1207+
Relation::morphMap(['alias2' => 'AnotherModel']);
1208+
$model = new EloquentModelStub;
1209+
$model2 = new EloquentModelCamelStub;
1210+
1211+
try {
1212+
$this->assertEquals('stub', $model->getMorphClass());
1213+
$this->assertEquals('alias', $model2->getMorphClass());
1214+
} finally {
1215+
Relation::morphMap([], false);
1216+
Relation::$tableNameAsMorphType = false;
1217+
}
1218+
}
1219+
12031220
public function testHasManyCreatesProperRelation()
12041221
{
12051222
$model = new EloquentModelStub;

0 commit comments

Comments
 (0)