QueryBuilder lastInsertId()

时间:2019-04-03 13:59:27

标签: typo3 query-builder extbase typo3-9.x

我想获得条目的最后一个UID。对于mysql,它是“ insertId()”。在Extbase中如何工作?

$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
$queryBuilder
   ->insert($table)
   ->values([
       'test_id'          => 1,
       'test2_id'         => 2,
   ]);

$queryBuilder->execute();

$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table2);
$queryBuilder
   ->insert($table2)
   ->values([
       'uid_local'         => ?, // uid from $table
       'uid_foreign'       => 1
   ]);
$queryBuilder->execute();

2 个答案:

答案 0 :(得分:1)

您可以使用$queryBuilder->getConnection()->lastInsertId();

获取最后一个插入ID。

这样就可以做到:

$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
$queryBuilder
   ->insert($table)
   ->values([
       'test_id'          => 1,
       'test2_id'         => 2,
   ]);

$queryBuilder->execute();
$tableUid = $queryBuilder->getConnection()->lastInsertId();

$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table2);
$queryBuilder
   ->insert($table2)
   ->values([
       'uid_local'         => $tableUid,
       'uid_foreign'       => 1
   ]);
$queryBuilder->execute();

答案 1 :(得分:0)

我不确定使用QueryBuilder插入新记录时是否可用,但是TYPO3 Docs中的迁移指南说明了如何在新的Doctrine数据库层中迁移sql_insert_id()方法

Here

提示:

(int)$databaseConnectionForPages->lastInsertId('pages');