Php Symfony2:持久化一个多个多个实体时的异常
我正在构建一个条目表单,其中嵌入了一个文件提交表单。这两个实体通过双向关系进行关联,如下所示:Php Symfony2:持久化一个多个多个实体时的异常,php,symfony,Php,Symfony,我正在构建一个条目表单,其中嵌入了一个文件提交表单。这两个实体通过双向关系进行关联,如下所示: class Entry { /** *@ORM\OneToMany(targetEntity="OOTN\BlogBundle\Entity\Image", mappedBy="Entry", cascade={"persist"}) *@ORM\JoinColumn(nullable=false) */ private $image;
class Entry
{
/**
*@ORM\OneToMany(targetEntity="OOTN\BlogBundle\Entity\Image", mappedBy="Entry", cascade={"persist"})
*@ORM\JoinColumn(nullable=false)
*/
private $image;
//rest of Entry class
class Image
{
/**
*@ORM\ManyToOne(targetEntity="OOTN\BlogBundle\Entity\Entry", cascade={"persist"})
*@ORM\JoinColumn(nullable=false)
*/
private $entry;
//attributes id, date, url and alt here
private $file;
public function upload()
{
if (null === $this->file)
{
return;
}
$name = $this->file->getClientOriginalName();
$this->file->move($this->getUploadRootDir(), $name);
$this->url = $name;
$this->alt = $name;
}
//functions getUploadDir and getUploadRootDir here
表单嵌入得很好,但是在持久化条目时,我得到一个sql错误,告诉我Image的条目id为null。我原以为symfony会自行处理,但我还是尝试在控制器中手动设置,如下所示:
$entry->getImage()->setEntry($entry);
public function __construct()
{
$this->image = new ArrayCollection();
//don't forget a "use Doctrine\Common\Collections\ArrayCollection;" statement
}
$listImages = $entry->getImage();
foreach($listImages as $image)
{
$entry->addImage($image);
$image->setEntry($entry);
$image->upload();
}
当我这样做时,不仅条目id为null,而且url和alt也为null。好像上传没有完成它的工作,但它确实完成了,因为文件确实被上传了。我真的搞不懂,有人知道发生了什么事吗?多亏了Ninir的评论,我才明白。在entry类中确实需要一个addImage方法,外加一个如下所示的构造函数:
$entry->getImage()->setEntry($entry);
public function __construct()
{
$this->image = new ArrayCollection();
//don't forget a "use Doctrine\Common\Collections\ArrayCollection;" statement
}
$listImages = $entry->getImage();
foreach($listImages as $image)
{
$entry->addImage($image);
$image->setEntry($entry);
$image->upload();
}
在控制器中,执行以下操作:
$entry->getImage()->setEntry($entry);
public function __construct()
{
$this->image = new ArrayCollection();
//don't forget a "use Doctrine\Common\Collections\ArrayCollection;" statement
}
$listImages = $entry->getImage();
foreach($listImages as $image)
{
$entry->addImage($image);
$image->setEntry($entry);
$image->upload();
}
它帮了我的忙。您是否可以尝试在Entry类中添加addImage方法并执行以下操作:1。将图像添加到条目2中。从图像中设置条目我想这是一个双向问题: