diff --git a/webfiori/framework/writers/TableClassWriter.php b/webfiori/framework/writers/TableClassWriter.php index 76440c1b..f8bdb596 100644 --- a/webfiori/framework/writers/TableClassWriter.php +++ b/webfiori/framework/writers/TableClassWriter.php @@ -14,6 +14,7 @@ use webfiori\database\Column; use webfiori\database\DataType; use webfiori\database\EntityMapper; +use webfiori\database\FK; use webfiori\database\mssql\MSSQLColumn; use webfiori\database\mssql\MSSQLTable; use webfiori\database\mysql\MySQLColumn; @@ -433,8 +434,60 @@ private function appendColObj($key, $colObj) { if ($colObj->getComment() !== null) { $this->append("ColOption::COMMENT => '".$colObj->getComment()."',", 4); } + $this->addFKOption($colObj); $this->append("],", 3); } + private function addFKOption(Column $colObj) { + $fks = $this->getTable()->getForeignKeys(); + foreach ($fks as $fk) { + $fk instanceof FK; + if (count($fk->getSourceCols()) == 1) { + $sourceCol = $fk->getSourceCols()[0]; + if ($colObj->getNormalName() == $sourceCol->getNormalName()) { + $this->addFKOptionHelper($colObj, $fk); + } + } + } + } + private function addFKOptionHelper(Column $col, FK $fk) { + $refTableNs = get_class($fk->getSource()); + $cName = $this->getNamespace().'\\'.$this->getName(); + $refTableClassName = '$this'; + + if ($cName != $refTableNs) { + $nsSplit = explode('\\', $refTableNs); + $refTableClassName = 'new '.$nsSplit[count($nsSplit) - 1].'()'; + } + $keyName = $fk->getKeyName(); + $sourceCol = array_keys($fk->getSourceCols())[0]; + $this->append("ColOption::FK => [", 4); + $this->append("ColOption::FK_NAME => '".$keyName."',", 5); + $this->append("ColOption::FK_TABLE => ".$refTableClassName.",", 5); + $this->append("ColOption::FK_COL => '".$sourceCol."',", 5); + $this->append("ColOption::FK_ON_UPDATE => ".$this->getFkCond($fk->getOnUpdate()).",", 5); + $this->append("ColOption::FK_ON_DELETE => ".$this->getFkCond($fk->getOnDelete()).",", 5); + $this->getTable()->removeReference($fk->getKeyName()); + $this->append("],", 4); + } + private function getFkCond(string $txt) { + switch ($txt) { + case 'cascade' :{ + return 'FK::CASCADE'; + } + case 'no action' :{ + return 'FK::NO_ACTION'; + } + case 'restrict' :{ + return 'FK::RESTRICT'; + } + case 'set default' :{ + return 'FK::SET_DEFAULT'; + } + case 'set null' :{ + return 'FK::SET_NULL'; + } + } + } /** * Extract and return the name of table class based on associated table object. *