Skip to content

Commit 5d5655b

Browse files
authored
Option to use table names when morphing (#38451)
* support class basenames on morphs * table name option for morphmap * rename method * fix test
1 parent 3ccba24 commit 5d5655b

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -731,7 +731,9 @@ public function getMorphClass()
731731
return array_search(static::class, $morphMap, true);
732732
}
733733

734-
return static::class;
734+
return Relation::$useTableNamesForMorphMap
735+
? $this->getTable()
736+
: static::class;
735737
}
736738

737739
/**

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,13 @@ abstract class Relation
5050
*/
5151
protected static $constraints = true;
5252

53+
/**
54+
* Indicates that table names should be used when determining morph classes.
55+
*
56+
* @var bool
57+
*/
58+
public static $useTableNamesForMorphMap = false;
59+
5360
/**
5461
* An array to map class names to their morph names in the database.
5562
*
@@ -376,6 +383,16 @@ protected function whereInMethod(Model $model, $key)
376383
: 'whereIn';
377384
}
378385

386+
/**
387+
* Indicate that the table names should be used when determining morphed class names.
388+
*
389+
* @return void
390+
*/
391+
public static function morphUsingTableNames()
392+
{
393+
static::$useTableNamesForMorphMap = true;
394+
}
395+
379396
/**
380397
* Set or get the morph map for polymorphic relations.
381398
*

tests/Database/DatabaseEloquentModelTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1217,6 +1217,16 @@ public function testMorphOneCreatesProperRelation()
12171217
$this->assertEquals(EloquentModelStub::class, $relation->getMorphClass());
12181218
}
12191219

1220+
public function testMorphOneCreatesProperRelationWhenUsingTableNames()
1221+
{
1222+
Relation::morphUsingTableNames();
1223+
$model = new EloquentModelStub;
1224+
$this->addMockConnection($model);
1225+
$relation = $model->morphOne(EloquentModelSaveStub::class, 'morph');
1226+
$this->assertEquals('stub', $relation->getMorphClass());
1227+
Relation::$useTableNamesForMorphMap = false;
1228+
}
1229+
12201230
public function testCorrectMorphClassIsReturned()
12211231
{
12221232
Relation::morphMap(['alias' => 'AnotherModel']);

0 commit comments

Comments
 (0)