原则2 -使用组合键持久化实体


doctrine 2 - persisting an entity with composite key

带复合键的Doctrine 2实体:

/**
 * @Entity 
 */
class Test
{
    /**
     * @Id
     * @Column (type="integer", length=11, name="id")
     *
     */
    protected $id = null;
    /**
     * @Id
     * @Column (type="integer", length=11, name="idtwo")
     *
     */
    protected $idtwo = null; 
    public function setIdTwo($id)
    {
        $this->idtwo = $id;
    }
    public function setId($id)
    {
        $this->id = $id;
    }
}

保存实体

$test = new Test();
$test->setId(1);
$test->setIdTwo(1);
$em->persist($test);

DB表:

CREATE TABLE `Bella_Test` (
  `id` int(11) NOT NULL,
  `idtwo` int(11) NOT NULL,
  PRIMARY KEY (`id`,`idtwo`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

预期结果:一行添加到db表中,有两个id字段,值都是1

实际结果:没有行被添加到db表中。没有抛出异常。

问题:怎么回事?

您可以使用try catch块来查看发生了什么

try{
    $em->flush(); //don't forget flush after persisting an object
}
catch(Exception $e){
   echo 'Flush Operation Failed: '.$e->getMessage();   
}

其他假设,在我看来,您的实体表名和DB表名可能不匹配。我认为试一试是个好主意

/**
 * @Entity 
 * @Table(name="Bella_Test")
 */
 .
 .
 .