Sonata Admin Bundle 一对多关系不保存外国 ID [英] Sonata Admin Bundle One-to-Many relationship not saving foreign ID
问题描述
我在将 SonataAdminBunle 与 symfony 2.2 结合使用时遇到了问题.我有一个 Project 实体和一个 ProjectImage 实体,并指定了这两者之间的一对多关系,如下所示:
I have a problem with the SonataAdminBunle in combination with symfony 2.2. I have a Project entity and a ProjectImage entity and specified a One-to-Many relationship between these two like so:
class Project
{
/**
* @ORM\OneToMany(targetEntity="ProjectImage", mappedBy="project", cascade={"all"}, orphanRemoval=true)
*/
private $images;
}
class ProjectImage
{
/**
* @ORM\ManyToOne(targetEntity="Project", inversedBy="images")
* @ORM\JoinColumn(name="project_id", referencedColumnName="id")
*/
private $project;
}
我已经配置了 ProjectAdmin 和 ProjectImageAdmin:
I've configured the ProjectAdmin and ProjectImageAdmin:
class ProjectAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('title')
->add('website')
->add('description', 'textarea')
->add('year')
->add('tags')
->add('images', 'sonata_type_collection', array(
'by_reference' => false
), array(
'edit' => 'inline',
'inline' => 'table',
'sortable' => 'id',
))
;
}
}
class ProjectImageAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('file', 'file', array(
'required' => false
))
;
}
}
问题是在数据库的project_image表中,project_id没有保存,其他数据都保存了,图片也保存了.在其他任何地方都找不到有效的答案.
The problem is that in the project_image table in the database the project_id is not saved, while all other data is and also the image is saved. Couldn't find a working answer anywhere else.
推荐答案
虽然无关,但我会稍微调整您的一对多注释:
Although unrelated, I'd slighty tweak your One-to-Many annotation:
class Project
{
/**
* @ORM\OneToMany(targetEntity="ProjectImage", mappedBy="project", cascade={"persist"}, orphanRemoval=true)
* @ORM\OrderBy({"id" = "ASC"})
*/
private $images;
}
回到正轨,您的注释和奏鸣曲管理表单看起来不错,所以我很确定您在 Project 实体类中缺少其中一种方法:
Back on track, your annotations and Sonata Admin forms look fine, so I'm pretty sure you're missing one of those methods in your Project entity class:
public function __construct() {
$this->images = new \Doctrine\Common\Collections\ArrayCollection();
}
public function setImages($images)
{
if (count($images) > 0) {
foreach ($images as $i) {
$this->addImage($i);
}
}
return $this;
}
public function addImage(\Acme\YourBundle\Entity\ProjectImage $image)
{
$image->setProject($this);
$this->images->add($image);
}
public function removeImage(\Acme\YourBundle\Entity\ProjectImage $image)
{
$this->images->removeElement($image);
}
public function getImages()
{
return $this->Images;
}
在您的管理员课程中:
public function prePersist($project)
{
$this->preUpdate($project);
}
public function preUpdate($project)
{
$project->setImages($project->getImages());
}
这篇关于Sonata Admin Bundle 一对多关系不保存外国 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!