两个实体画廊相册 and 画廊图片具有 OneToMany/ManyToOne 关系:
One GalleryAlbum ==== can have ====> Many GalleryImage
Many GalleryImage === can be in ===> One GalleryAlbum
(来源如下)
问题是什么?
添加(上传)文件到图库相册
$em->坚持($专辑)
$em->flush()
对于每个上传的文件 GalleryAlbum 类创建一个新的 GalleryImage 实体并将其添加到 $images
我的 ECHO/EXIT 测试未显示(GalleryImage 名为 preUpload 的 prePersist/preUpdate 事件回调函数未触发!)
我的新图像没有保存到数据库中?为什么?
有什么奇怪的! If I do:
添加(上传)文件
$em->坚持($专辑)
$em->flush()
再次 $em->flush()
显示了我的 ECHO/EXIT 测试(触发了 GalleryImage 名为 preUpload 的 prePersist/preUpdate 事件回调函数!)
(如果我删除 echo/exit)我的新 GalleryImages 现在已保存!
Why?
为什么我flush()一次就不会触发preUpload,而flush()两次就触发preUpload?
# src GalleryAlbum.php
/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
* @ORM\Table(name="gallery_album")
*/
class GalleryAlbum
{
// some properties like id, name, description, etc
/**
* @ORM\OneToMany(targetEntity="GalleryImage", mappedBy="parent")
*/
protected $images;
/* Files container. Used for upload service. Must not be persisted. */
protected $files;
/* @ORM\Column(type="boolean", nullable=TRUE)
*
* if set to true will updateing object and calling preUpdate event callback
* becouse it's always set to null in database by prePersist event callback */
protected $files_added;
/**
* Set container files
*
* @return GalleryAlbum
*/
public function setFiles($files)
{
$this->files = $files;
$this->files_added = true;
/* setting files_added to true forces EntityManager to update
* this GalleryAlbum even if no other properties have changed */
return $this;
}
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUpload()
{
if(null !== $this->files) {
foreach($this->files as $key => $file) {
$this->addGalleryElement($file);
unset($this->files[$key]);
}
}
/* Resetting property files_added to NULL
* so it always stays null in database */
$this->files_added = null;
}
/**
* Constructing new GalleryImage and setting it's file and parent
*/
public function addGalleryElement($file)
{
$element = new GalleryImage($this, $file);
$this->addGalleryImage($element);
}
}
# src GalleryImage.php
/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
* @ORM\Table(name="gallery_image")
*/
class GalleryImage
{
// some properties like id, name, description, etc
/**
* @ORM\ManyToOne(targetEntity="GalleryAlbum", inversedBy="images")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
*/
protected $parent;
/* Constructing new GalleryImage */
public function __construct($parent = null, $file = null)
{
if($parent) $this->setParent($parent);
if($file) $this->setFile($file);
}
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUpload()
{
echo 'TEST: is this event callback function fired?'; exit;
if(null !== $this->file) {
$this->path = $this->file->guessExtension();
}
$this->file_added = null;
}
}