使用2个表和QueryBuilder执行简单的UPDATE sql语句

时间:2018-03-19 10:38:23

标签: typo3

我正在编写TYPO3 8.x及更高版本的扩展程序。我想要使用已弃用的$ GLOBALS [' TYPO3_DB'] - > exec_ *函数。

我有一个简单的SQL语句,应该在class.ext_update.php类中使用,以便迁移数据:

update table1 as t1,table2 as t2 set t1.field1=t2.field2 where t1.uid=t2.uid;

如您所见,没有用户输入,不需要引用任何内容。因此,我最好寻找一种使用原始SQL查询的方法。

始终为特定表明确设置QueryBuilder。您可以做的是加入,但我没有使用更新。

$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
    ->getQueryBuilderForTable('table1');

$queryBuilder->update('table1')
   ->join(
       'table1', 
       'table2', 
       't2',
       $queryBuilder->expr()->eq(
           't2.uid', 
           $queryBuilder->quoteIdentifier('table1.uid')
       )
   )
   ->set(
       'table1.field1', 
       $queryBuilder->quoteIdentifier(
           't2.field2'
       ), 
       false
   )->execute();

"执行' UPDATE table1设置table1时发生异常。field1 = t2field2& #39 ;:未知栏' t2.field2'在'字段列表'"

更新

$ queryBuilder-> getSQL()返回:

UPDATE `table1` SET `table1`.`field1` = `t2`.`field2`  

好的,所以没有应用加入。我无论如何只在文档中找到了SELECT + JOIN的例子,这显然不是它应该做的方式。

1 个答案:

答案 0 :(得分:2)

正式的TYPO3文档声明:

  

对join()方法的调用仅考虑 - > select()和    - > count()类型查询。 - > delete(), - > insert()和update()不支持连接,这些查询部分会被忽略,并且不会在   最后陈述。

     

https://docs.typo3.org/typo3cms/CoreApiReference/ApiOverview/Database/QueryBuilder/Index.html#join-innerjoin-rightjoin-and-leftjoin

这是Doctrine DBAL强加的限制。

您可以使用Doctrine连接对象的executeQuery或最好是executeUpdate来执行原始查询。没有经过测试的例子,但这样的事情应该有用。:

$updateQuery = "UPDATE table1
                SET $connection->quoteIdentifier('table1.field1') = $connection->quoteIdentifier('table2.field2')
                WHERE $connection->quoteIdentifier('table1.uid') = $connection->quoteIdentifier('table2.uid')"; 
$connection->executeQuery($updateQuery);
相关问题