在Doctrine2/Symfony2上插入实体时出现id错误


Error with id on INSERT INTO entity on Doctrine2/Symfony2

几天以来,我的一个实体出现了问题。该实体的ID需要手动定义(没有自动增量)。但是当我尝试定义它时,Doctrine在插入查询时返回一个错误:

DBALException:执行INSERT INTO infoosperso (num、login、nom、prename、email、societe、adr1、adr2、cp、ville、tel、fax、nichandle、parrain、actif、state、emailvalidate、date_creation、id_entite_legale_pays、pays) VALUES(?)时发生异常。, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' 与params[空,"Test","Hebert","Donovan","test@mail.com","SNCF","临时excepteur木棒molestiae sed temporibus设计系错误illo临时et amet voluptatum韦尔莫迪cupiditate","Laboriosam eiusmod悲哀非saepe incidunt cillum corrupti occaecat dolorem临时aut,存在autem","13001","Marseille","0442910000",0442499569", 0, null, 1,0, 1, "2015-06-04 11:09:46.000", null, 171]:

SQLSTATE[HY000]: General error: 515 General SQL Server error: Check messages from SQL Server [515] (severity 16) [(null)]

下面是我当前的代码:

$infosPerso = new InfosPerso();
$infosPerso->setLogin($client->getLogin())
->setParrain($leaderBmcId)
->setNicHandle(0)
->setNom($client->getName())
->setPrenom($client->getFirstname())
->setEmail($client->getEmail())
->setAdr1($client->getAddress())
->setAdr2($client->getComplementaryAddress())
->setCp($client->getZipCode())
->setDateCreation($client->getCreationDate())
->setTel($client->getPhone())
->setFax($client->getFax())
->setVille($client->getCity())
->setPays($client->getCountry())// Entity Pays
->setSociete($client->getCompany()->getLibCompanies())
->setEmailValide(true)
->setState(0)
->setActif(1);

ID的实体定义:

/**
 * @var integer $num
 *
 * @ORM'Column(name="num", type="integer")
 * @ORM'Id
 * @ORM'GeneratedValue(strategy="CUSTOM")
 * @ORM'CustomIdGenerator(class="BizDatasBundle'Database'BMC'InfosPersoIdGenerator")
 */
private $num;

InfosPersoIdGenerator类的定义如下:

<?php
namespace BizDatasBundle'Database'BMC;
use Doctrine'ORM'Id'AbstractIdGenerator;

class InfosPersoIdGenerator extends AbstractIdGenerator
{
    public function generate('Doctrine'ORM'EntityManager $em, $entity)
    {
        $maxId = $em->createQueryBuilder('ip')
                    ->select('MAX(ip.num)')
                    ->from('BizDatasBundle:BMC''InfosPerso', 'ip')
                    ->getQuery()
                    ->getSingleScalarResult();
        $maxId++;
        return $maxId;
    }
}

如果我对$maxId执行回显,它将打印要设置的正确ID。但是当Doctrine刷新时,查询中的ID被设置为NULL,我不知道为什么。

如果你有一个想法。谢谢!

好的,让我们看看:

您说转储$maxId返回正确的值,但是如果您仔细查看您提供的代码,您实际上没有将值设置为InfosPerso。更有可能你错过了->setNum( $maxId )

顺便说一下,你可以清楚地看到,在SQL查询:
INSERT INTO InfosPerso (num...) // and the rest of your columns here

和紧跟其后的

with params [null,...]

可以看到,您没有为列提供值。

作为最后一个注意,如果你要自己生成ID,你可以移除GeneratedValue注释。引用自文档:

NONE:告诉Doctrine标识符是由你的代码分配的(并因此生成的)。分配必须在将新实体传递给EntityManager#persist之前进行。NONE等于完全不使用@GeneratedValue。