繁体   English   中英

Symfony 3.4中的删除/截断表无法正常工作

[英]Delete / Truncate table in Symfony 3.4 not working as it should

我正在尝试使用Symfony 3.4导入数据。 我已经成功完成了任务。 最后,我遇到了一些问题,但我不知道如何解决。 所以,我在做什么:

  • 从Excel文件中获取数据并将其存储在数据库中。

  • 刷新后,我删除表,然后再次浏览excel文件并将值存储在数据库中

我刚刚看到主键正在更新。 这不是问题,但是困扰我。 因此,如果我添加130行,将其删除,然后再次存储,主键将从260开始,然后从390返回,依此类推。

因此,我决定不删除表,而是截断它。 并第一次创建130行。 刷新时,它会截断表,但只存储5行而不是130行,而且我找不到该bug。 因此,在删除时一切正常,但是在截断时,第二次它仅存储五行而不是130行。这是我的代码,如果有人看到该错误,请告诉我:

public function importMappedAttributes($mappedAttributesValues)
{

    if (!$this->checkIfTableIsEmpty()) {
        $this->truncateTable();
    }

    try{

       foreach ($mappedAttributesValues as $value) {
            $mappedAttributes = new MappedAttribute();

            $mappedAttributes->setAkeneoAttribute($value['result_one']);
            $mappedAttributes->setXmlAttribute($value['result_two']);
            $mappedAttributes->setXmlPath($value['result_three']);
            $mappedAttributes->setMetadata($value['result_four']);

            $this->getEntityManager()->persist($mappedAttributes);
            $this->getEntityManager()->flush();

        }
    } catch (\Exception $e){

        throw new \Exception('Something went wrong!');

    }
}

第一部分检查表是否为空,以及是否没有截断它:

private function checkIfTableIsEmpty() {

    $numberOfRows = count($this->getEntityManager()->getRepository('ImportAttributesBundle:MappedAttribute')->findAll());

    if ($numberOfRows > 1) {

        return false;

    }

    return true;
}

public function truncateTable() {
    $em = $this->getEntityManager();
    $classMetaData = $em->getClassMetadata('ImportAttributesBundle:MappedAttribute');
    $connection = $em->getConnection();
    $dbPlatform = $connection->getDatabasePlatform();
    try {
        $connection->query('SET FOREIGN_KEY_CHECKS=0');
        $q = $dbPlatform->getTruncateTableSql($classMetaData->getTableName());
        $connection->executeUpdate($q);
        $connection->query('SET FOREIGN_KEY_CHECKS=1');
        $connection->commit();

    }
    catch (\Exception $e) {
        $connection->rollback();
    }
}

问题是$ this-> getEntityManager()-> flush(); 应该走在foreach之外。 这导致了意外的行为,当我将它放在foreach之后时,一切工作正常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM