/** * Gets the table definition of an existing table in the database * @param string $name Name of the table * @return zibo\library\database\definition\Table Table definition * @throws zibo\library\database\mysql\exception\MysqlException */ public function getTable($name) { $this->validateName($name); if (array_key_exists($name, $this->tables)) { return $this->tables[$name]; } $table = new Table($name); $fields = $this->getTableFields($name); foreach ($fields as $field) { $table->addField($field); } $foreignKeys = $this->getTableForeignKeys($name); foreach ($foreignKeys as $foreignKey) { $table->setForeignKey($foreignKey); } $indexes = $this->getTableIndexes($table); foreach ($indexes as $index) { $table->addIndex($index); } $this->tables[$name] = $table; return $table; }
public function testHasForeignKey() { $table = new Table('table'); $field = new Field('field', 'type'); $foreignKey = new ForeignKey('field', 'table2', 'id'); $table->addField($field); $table->setForeignKey($foreignKey); $this->assertTrue($table->hasForeignKey('field')); $this->assertFalse($table->hasForeignKey('unexistant')); }
/** * Get the database table definition of this model * @return zibo\library\database\definition\Table */ public function getDatabaseTable() { $table = new Table($this->name); foreach ($this->fields as $fieldName => $field) { if ($field->isLocalized() || $field instanceof HasManyField || $field instanceof HasOneField) { continue; } $table->addField($field); if ($field instanceof BelongsToField) { $name = $this->name . '_' . ucfirst($fieldName); if (strlen($name) > 64) { $name = '_' . ucfirst($fieldName); $name = substr($this->name, 0, 64 - strlen($name)) . $name; } $foreignKey = new ForeignKey($fieldName, $field->getRelationModelName(), self::PRIMARY_KEY, $name); $table->setForeignKey($foreignKey); } } foreach ($this->indexes as $index) { $fields = $index->getFields(); foreach ($fields as $field) { if ($field->isLocalized()) { continue 2; } } $table->addIndex($index); } return $table; }