Consider foreign key constraints with isRelationNullable (#1231)

* Consider foreign key constraints with isRelationNullable

* test: add belongsTo Variation

* command: composer test-regenerate
This commit is contained in:
atsu.kg
2021-08-07 13:31:20 +02:00
committed by GitHub
parent b268871c16
commit 52a4b64656
4 changed files with 134 additions and 3 deletions
+24
View File
@@ -102,6 +102,10 @@ class ModelsCommand extends Command
* @var bool[string]
*/
protected $nullableColumns = [];
/**
* @var string[]
*/
protected $foreignKeyConstraintsColumns = [];
/**
* During initialization we use Laravels Date Facade to
@@ -452,6 +456,7 @@ class ModelsCommand extends Command
return;
}
$this->setForeignKeys($schema, $table);
foreach ($columns as $column) {
$name = $column->getName();
if (in_array($name, $model->getDates())) {
@@ -726,6 +731,11 @@ class ModelsCommand extends Command
$fkProp = $reflectionObj->getProperty('foreignKey');
$fkProp->setAccessible(true);
if ($relation === 'belongsTo') {
return isset($this->nullableColumns[$fkProp->getValue($relationObj)]) ||
!in_array($fkProp->getValue($relationObj), $this->foreignKeyConstraintsColumns, true);
}
return isset($this->nullableColumns[$fkProp->getValue($relationObj)]);
}
@@ -1409,4 +1419,18 @@ class ModelsCommand extends Command
$hookInstance->run($this, $model);
}
}
/**
* @param \Doctrine\DBAL\Schema\AbstractSchemaManager $schema
* @param string $table
* @throws DBALException
*/
protected function setForeignKeys($schema, $table)
{
foreach ($schema->listTableForeignKeys($table) as $foreignKeyConstraint) {
foreach ($foreignKeyConstraint->getLocalColumns() as $columnName) {
$this->foreignKeyConstraintsColumns[] = $columnName;
}
}
}
}