2

I'm using Silex with Doctrine DBAL. I try to create a table:

$schema = new \Doctrine\DBAL\Schema\Schema();
$table = $schema->createTable('admins');
$table->addColumn('id', 'smallint', array('unsigned' => true, 'autoincrement' => true));
$table->addColumn('username', 'string', array('length' => 10));
$table->addColumn('password', 'string', array('length' => 45));
$table->setPrimaryKey(array('id'));
$table->addUniqueIndex(array('username'));

$queries = $schema->toSql(new \Doctrine\DBAL\Platforms\PostgreSqlPlatform());
// or $queries = $schema->toSql(new \Doctrine\DBAL\Platforms\MysqlPlatform());
foreach ($queries as $query)
{
  echo $query . ";\n";
}

This is the output for the MySQL platform:

CREATE TABLE admins (
id SMALLINT UNSIGNED AUTO_INCREMENT NOT NULL,
username VARCHAR(10) NOT NULL,
password VARCHAR(45) NOT NULL,
UNIQUE INDEX UNIQ_A2E0150FF85E0677 (username), PRIMARY KEY(id)
) ENGINE = InnoDB;

It's absolutely right ! We can notice the "AUTO_INCREMENT" for the "id" column.

But If I choose the PostgreSQL platform, this is the output:

CREATE TABLE admins (
id SMALLINT NOT NULL,
username VARCHAR(10) NOT NULL,
password VARCHAR(45) NOT NULL, 
PRIMARY KEY(id)
);
CREATE UNIQUE INDEX UNIQ_A2E0150FF85E0677 ON admins (username);

The auto_increment doesn't work on PostgreSQL platform... But in the documentation, "autoincrement" is in the "Portable options" section. What's the problem ?

Thank you

4

1 回答 1

2

您需要手动创建序列或使用序列类型,因为 PostgreSQL 平台上不存在类似魔术标志的 AUTO_INCREMENT。它被记录为“便携式”,因为 DBAL 可以在所有平台上处理此要求,但通过不同的方式。

尝试这个:

$table = $schema->createTable('admins');
$schema->createSequence('admins_seq');
$table->addColumn('id', 'smallint', array('unsigned' => true));
$table->addColumn( ... );
// ...

希望能帮助到你。

更新:啊,评论后我想我知道发生了什么。@Thomas,您是如何以及从何处获得该$schema实例的?的输出是get_class($schema)什么?

您必须使用可以从实例中轻松获取的Schema Manager$connection实例,并且您应该在该实例上发出命令以获得最大的可移植性。

例子:

$sm = $connection->getSchemaManager();
$table = new \Doctrine\DBAL\Schema\Table('admin');
$id = $table->addColumn('id', 'integer');
$id->setAutoincrement(true); 
$table->addColumn('username', 'string');
$sm->createTable($table);

这应该有效。

于 2014-06-01T18:49:15.340 回答