如何为单个Doctrine表生成SQL?

时间:2015-04-14 02:21:41

标签: php doctrine-orm

我有这段代码:

$schema = $connection->getSchemaManager()->createSchema();

        if(!$schema->hasTable($name)) {

            $table  = $schema->createTable( $name );

            $table->addColumn('id','integer',['unsigned' => true]);
            $table->addColumn('string','string',['length'=> 64]);
            $table->addColumn('floats','float');
            $table->addColumn('integers','integer');
            $table->addColumn('date_time','datetime');

            ($schema->toSql( $connection->getDatabasePlatform() ));
            $connection->query( $schema->toSql( $connection->getDatabasePlatform() ) )[0] );
);

我已成功创建带查询的表:

array (size=1)
  0 => string 'CREATE TABLE level1 (id INT UNSIGNED NOT NULL...

但是当第二次执行时,也创建了最后一个查询,所以我只是从数组中获取最后一个查询:

array (size=2)
  0 => string 'CREATE TABLE level1 (id INT UNSIGNED NOT NULL...
  1 => string 'CREATE TABLE level2 (id INT UNSIGNED NOT NULL...

但是当一堆桌子存在时,我得到了

0 => string 'CREATE TABLE level1 (id INT UNSIGNED NOT NULL...
  1 => string 'CREATE TABLE position (id INT AUTO_INCREMENT NOT NULL...
  2 => string 'CREATE TABLE user (id INT AUTO_INCREMENT NOT NULL...
  3 => string 'CREATE TABLE level2 (id INT UNSIGNED NOT NULL, string VARCHAR(64) NOT NULL, floats DOUBLE PRECISION NOT NULL...
  4 => string 'ALTER TABLE user ADD CONSTRAINT FK_8D93D649A76ED395 FOREIGN KEY (user_id) REFERENCES position (id)

很难指出正确的查询。

有没有为单个创建表创建查询?

该表需要按需创建并通过脚本创建,而不是cli,并且我没有@Entity Class。

1 个答案:

答案 0 :(得分:2)

SchemaManager有许多公共方法,它们将为完整模式SQL的不同组件提供SQL。默认情况下,getCreateTableSQL()方法将为表及其索引创建SQL,但可以覆盖该行为。

    /** @var Doctrine\DBAL\Connection $connection */
    $connection = ...;
    $name = ...;
    $schemaManager = $connection->getSchemaManager();
    $schema = $schemaManager->createSchema();

    if(!$schema->hasTable($name)) {

        $table = $schema->createTable($name);

        $table->addColumn('id', 'integer', ['unsigned' => true]);
        $table->addColumn('string', 'string', ['length' => 64]);
        $table->addColumn('floats', 'float');
        $table->addColumn('integers', 'integer');
        $table->addColumn('date_time', 'datetime');
        $sql = $schemaManager->getDatabasePlatform()->getCreateTableSQL($table);
        $connection->query($sql);
    }