【问题标题】:TYPO3 alter table with QuerybuilderTYPO3 使用 Querybuilder 更改表
【发布时间】:2020-11-17 16:45:03
【问题描述】:

如何使用 TYPO3 9 Querybuilder 执行“ALTER TABLE”命令?

ALTER TABLE foo
  DROP INDEX bar;

应该使用这个类来执行查询:

use TYPO3\CMS\Core\Database\ConnectionPool;

...
$table = 'foo';
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);

或者是否有必要实例化另一个数据库对象,例如派生自 Doctrine\DBAL\Schema\Schema 类。

【问题讨论】:

    标签: typo3 query-builder


    【解决方案1】:

    试试看,这可能对你有帮助。但是,我之前从未尝试过更改表命令(从不需要!!)

    $connection = $this->objectManager->get(ConnectionPool::class)->getConnectionForTable($table);
    $statement = $this->objectManager->get(
                       \Doctrine\DBAL\Statement::class
                       'ALTER TABLE foo DROP INDEX bar',
                       $connection
                 );
    
    $query = $this->createQuery();
    $query->statement($statement);
    

    【讨论】:

    • 至少在 v10.x 中你应该使用 GeneralUtility::makeInstance(ConnectionPool::class) 而不是 ObjectManager
    • 感谢@Naderio 纠正我!我找到了参考here!正如我所说,我从未使用过;)
    • ObjectManager::get 在 TYPO3 10 LTS 中已被标记为已弃用。 forge.typo3.org/issues/90803 而且我没有 Extbase 类,因此没有 $this->objectManager 对象。
    【解决方案2】:

    这应该做的工作:

    use TYPO3\CMS\Core\Utility\GeneralUtility;
    use TYPO3\CMS\Core\Database\ConnectionPool;
    
    // ...
    
    GeneralUtility::makeInstance(ConnectionPool::class)
        ->getConnectionForTable('foo')
        ->exec('ALTER TABLE foo DROP INDEX bar;');
    

    文档警告关于在存储库之外使用查询: https://docs.typo3.org/m/typo3/book-extbasefluid/master/en-us/6-Persistence/3-implement-individual-database-queries.html

    【讨论】:

    • 此解决方案有效。能否也加一下use TYPO3\CMS\Core\Database\ConnectionPool;
    【解决方案3】:

    另一种解决方案是在这种情况下使用 Doctrine Schema Manager:

    use \TYPO3\CMS\Core\Utility\GeneralUtility;
    use \TYPO3\CMS\Core\Database\ConnectionPool;
    
    $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('foo');
    $connection->getSchemaManager()->dropIndex('bar', 'foo');
    

    【讨论】:

      猜你喜欢
      • 2021-02-12
      • 2021-09-12
      • 2023-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-19
      • 1970-01-01
      相关资源
      最近更新 更多