Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Add table name as default morph type #35257

Merged
merged 1 commit into from Nov 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
17 changes: 17 additions & 0 deletions tests/Database/DatabaseEloquentModelTest.php
Expand Up @@ -1200,6 +1200,23 @@ 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);
Relation::$tableNameAsMorphType = false;
}
}

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