如何在 Symfony 的 CLI 命令中在 TYPO3 v9 中创建文件关系?

How to create a file relation in TYPO3 v9 in a CLI command from Symfony?

我使用 TYPO3 9.5.4 中的新 Symfony 命令创建了一个迁移命令,用于将数据从另一个 cms 导入 TYPO3。唯一的问题是在我导入的数据和它们的图像之间建立关系。 TYPO3 documentation 中的示例对我不起作用。

我创建我的新实体(例如产品)并调用我的方法“addBackendFileRelation”来创建上传文件(数据库中存在记录)和我的新产品(数据库中存在记录)之间的文件关系。

public function addBackendFileRelation( int $uid, string $table, string $field, File $file ): bool {
    $resourceFactory = GeneralUtility::makeInstance( ResourceFactory::class );

    try {
        $fileObject = $resourceFactory->getFileObject( $file->getUid() );
        $objectUid = $fileObject->getUid();
    } catch ( FileDoesNotExistException $e ) {
        return false;
    }
  
    $record = BackendUtility::getRecord( $table, $uid );
    $newId = 'NEW1234';
    $data = [];
    $data['sys_file_reference'][$newId] = [
        'table_local' => 'sys_file',
        'uid_local' => $objectUid,
        'tablenames' => $table,
        'uid_foreign' => $uid,
        'fieldname' => $field,
        'pid' => $record['pid'],
    ];
    $data[$table][$uid] = [
        $field => $newId,
        'pid' => $record['pid'],
    ];
    $dataHandler = GeneralUtility::makeInstance( DataHandler::class );
    $dataHandler->start( $data, [] );
    $dataHandler->process_datamap();

    foreach ( $dataHandler->errorLog as $log ) {
        var_dump( $log );
    }

    $fileRefUid = $dataHandler->substNEWwithIDs[$newId];

    return (int)$fileRefUid > 0;
}

DataHandler 的错误日志打印如下:
[1.2.1]: Attempt to modify table 'sys_file_reference' without permission.

那么我可以做些什么来创建关系呢?为 cli 创建后端用户对我不起作用。

[编辑] 解决方案

使用教程示例 (link from the comments) 它有效。我在尝试创建关系之前调用了方法:

    public function execute() {
      // authenticate CommandLineUserAuthentication user for DataHandler usage
      $GLOBALS['BE_USER']->backendCheckLogin();

      // [...]

      $this->addBackendFileRelation( $uid, $table, $field, $file );

      // [...]
    }

解决方案在评论和编辑的问题中。在尝试使用 DataHandler 之前仅使用 $GLOBALS['BE_USER']->backendCheckLogin()