Skip to content

Commit

Permalink
Option to use table names when morphing (laravel#38451)
Browse files Browse the repository at this point in the history
* support class basenames on morphs

* table name option for morphmap

* rename method

* fix test
  • Loading branch information
taylorotwell authored and Krisell committed Aug 20, 2021
1 parent 0582bce commit 8742956
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -731,7 +731,9 @@ public function getMorphClass()
return array_search(static::class, $morphMap, true);
}

return static::class;
return Relation::$useTableNamesForMorphMap
? $this->getTable()
: static::class;
}

/**
Expand Down
17 changes: 17 additions & 0 deletions src/Illuminate/Database/Eloquent/Relations/Relation.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ abstract class Relation
*/
protected static $constraints = true;

/**
* Indicates that table names should be used when determining morph classes.
*
* @var bool
*/
public static $useTableNamesForMorphMap = false;

/**
* An array to map class names to their morph names in the database.
*
Expand Down Expand Up @@ -376,6 +383,16 @@ protected function whereInMethod(Model $model, $key)
: 'whereIn';
}

/**
* Indicate that the table names should be used when determining morphed class names.
*
* @return void
*/
public static function morphUsingTableNames()
{
static::$useTableNamesForMorphMap = true;
}

/**
* Set or get the morph map for polymorphic relations.
*
Expand Down
10 changes: 10 additions & 0 deletions tests/Database/DatabaseEloquentModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1217,6 +1217,16 @@ public function testMorphOneCreatesProperRelation()
$this->assertEquals(EloquentModelStub::class, $relation->getMorphClass());
}

public function testMorphOneCreatesProperRelationWhenUsingTableNames()
{
Relation::morphUsingTableNames();
$model = new EloquentModelStub;
$this->addMockConnection($model);
$relation = $model->morphOne(EloquentModelSaveStub::class, 'morph');
$this->assertEquals('stub', $relation->getMorphClass());
Relation::$useTableNamesForMorphMap = false;
}

public function testCorrectMorphClassIsReturned()
{
Relation::morphMap(['alias' => 'AnotherModel']);
Expand Down

0 comments on commit 8742956

Please sign in to comment.