我对Doctrine \ ORM \ Mapping问题感到困惑。我有两个实体,它们是多对一,单向关联。我想操作Chipinfo(添加/更新/删除)而不影响生产者。只有坚持Chipinfo而没有坚持生产者..
class Chipinfo implements
{
/**
* @var integer
*
* @ORM\Column(name="ChipID", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $chipid;
/**
* @var \Shop\Entity\Producer
*
* @ORM\ManyToOne(targetEntity="Shop\Entity\Producer")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="pId", referencedColumnName="producerid")
* })
*/
protected $pid;
}
class Producer{
/**
* @ORM\Id
* @ORM\Column(name="producerid", type="integer");
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $producerId;
/**
* @ORM\Column(name="producername", type="string")
*/
protected $producerName;
}
ChipInfo和Producer是多对一的单向关系:chipinfo只能由一个生产者构建,而一个生产者可以构建多个chipinfos。我想要的是:在Chipinfo中添加/更新/删除项目不会对Producer产生任何影响。
$chip = new Chipinfo();
$formData = $this->initFormData($form->getData());
$chip->populate($formData);
$this->getEntityManager()->persist($chip);
$this->getEntityManager()->flush();
private function initFormData(&$raw){
$raw['eid'] = new Encapuser($this->findEntity("Shop\Entity\Encapuser", $raw['eid']));
$this->log($raw->eid);
$raw['vid'] = new Vendors($this->findEntity("Shop\Entity\Vendors", $raw['vid']));
$raw['pid'] = new Producer($this->findEntity("Shop\Entity\Producer", $raw['pid']));
$this->log($raw);
return $raw;
}
会抛出错误:
A new entity was found through the relationship 'Shop\Entity\Chipinfo#pid' that was not configured to cascade persist operations for entity: Shop\Entity\Producer@00000000349002ee00000000c955fd11. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement 'Shop\Entity\Producer#__toString()' to get a clue.
然后我将pid配置为:
@ORM\ManyToOne(targetEntity="Shop\Entity\Producer", cascade={"persist"})
虽然错误消失了,但这不是我想要的。因为当我用现有的生产者A调用chipinfo的flush()时,会插入一个重复的新A.
因此,我的问题是: 1)我应该如何配置@manyToone字段,我没有从http://doctrine-orm.readthedocs.org/en/2.0.x/reference/working-with-associations.html#transitive-persistence-cascade-operations获得线索
2)我应该添加: @ORM \ OneToMany,targetEntity =“Shop \ Entity \ Producer” 私人@chip;
在制片人?如果是这样,生产者的操作(添加/删除/更新)是否需要构建一个@chip?
答案 0 :(得分:1)
您必须在实体的$ pid字段中设置现有生产者(由学说检索的实体)。
为什么要创建新的制作人? findEntity做什么?它似乎没有从Doctrine中检索实际的实体,为什么会这样?
通常你会这样做:
$chip->setPid($this->getEntityManager()->getRepository('Shop\Entity\Producer')->find($pid));