将实体添加到doctrine ArrayCollection时添加外键引用

时间:2013-01-07 12:51:21

标签: mysql zend-framework doctrine doctrine-orm

将实体添加到父实体的Doctrine ArrayCollection时,我收到以下错误。

Integrity constraint violation: 1048 Column 'job_fk' cannot be null

这是父母entiry

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Persistence\PersistentObject;

class Job extends \Doctrine\Common\Persistence\PersistentObject
{

    /**
     * @var integer $pk
     * @ORM\Column(name="pk", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
     protected $pk;

    /**
     * @ORM\OneToMany(targetEntity="Ajfit\Entity\JobRequirement", mappedBy="jobFk", fetch="LAZY", cascade={"persist"})
     */
    protected $requirements;

    public function __construct(){
         $this->requirements = new ArrayCollection();
    }
}

这是子实体

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Persistence\PersistentObject;

class JobRequirement extends \Doctrine\Common\Persistence\PersistentObject
{

    /**
     * @var integer $pk
     * @ORM\Column(name="pk", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
     protected $pk;

    /**
     * @ORM\Column(name="job_fk", type="integer")
     * @ORM\ManyToOne(targetEntity="Ajfit\Entity\Job", inversedBy="requirements" )
     * @ORM\JoinColumn(name="job_fk", referencedColumnName="pk")
     */
     protected $jobFk;

}

这是调用代码

$job = new Ajfit\Entity\Job();

foreach ($addedRequirements as $requirementText)
{
    $requirement = new \Ajfit\Entity\JobRequirement();
    $job->getRequirements()->add($requirement);
}

子实体添加正常,但jobFk根本没有设置。我在连接上有cascade = {“persist”},当我添加所有孩子时,我坚持所有,我的问题是,在添加孩子之前我是否需要坚持父母?或者我错过了什么?

谢谢你的时间。

安德鲁

1 个答案:

答案 0 :(得分:0)

尝试在JobRequirement中删除行@ORM \ Column(name =“job_fk”,type =“integer”)并再次检出。如果有效,请告诉我。