Skip to content

Commit

Permalink
add table name as default morph type
Browse files Browse the repository at this point in the history
  • Loading branch information
imanghafoori1 committed Nov 17, 2020
1 parent acb4b77 commit cc13615
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
Expand Up @@ -731,6 +731,10 @@ public function getMorphClass()
return array_search(static::class, $morphMap, true);
}

if (Relation::$tableNameAsMorphType) {
return $this->getTable();
}

return static::class;
}

Expand Down
17 changes: 17 additions & 0 deletions src/Illuminate/Database/Eloquent/Relations/Relation.php
Expand Up @@ -55,6 +55,13 @@ abstract class Relation
*/
public static $morphMap = [];

/**
* Indicates if the morph relation type should default to table name.
*
* @var bool
*/
public static $tableNameAsMorphType = false;

/**
* Create a new relation instance.
*
Expand Down Expand Up @@ -341,6 +348,16 @@ public static function morphMap(array $map = null, $merge = true)
return static::$morphMap;
}

/**
* Changes the default morph type to table name.
*
* @return void
*/
public static function tableNameAsMorphType()
{
self::$tableNameAsMorphType = true;
}

/**
* Builds a table-keyed array from model class names.
*
Expand Down
16 changes: 16 additions & 0 deletions tests/Database/DatabaseEloquentModelTest.php
Expand Up @@ -1200,6 +1200,22 @@ public function testCorrectMorphClassIsReturned()
}
}

public function testCorrectMorphClassIsReturnedOnChangingDefault()
{
Relation::tableNameAsMorphType();
Relation::morphMap(['alias' => EloquentModelCamelStub::class]);
Relation::morphMap(['alias2' => 'AnotherModel']);
$model = new EloquentModelStub;
$model2 = new EloquentModelCamelStub;

try {
$this->assertEquals('stub', $model->getMorphClass());
$this->assertEquals('alias', $model2->getMorphClass());
} finally {
Relation::morphMap([], false);
}
}

public function testHasManyCreatesProperRelation()
{
$model = new EloquentModelStub;
Expand Down

0 comments on commit cc13615

Please sign in to comment.