Две сущности GalleryAlbumи GalleryImageимеют отношение OneToMany/ManyToOne:
Один GalleryAlbum ==== может иметь === => Многие GalleryImage
Многие GalleryImage === могут находиться в ===> One GalleryAlbum
(исходники ниже)
В чем проблема?
Добавление (загрузка) файлов в GalleryAlbum
$ em->persist($album)
$em->flush()
Для каждого загружаемого файла класс GalleryAlbum создает и добавляет к $images новый объект GalleryImage
Мой тест ECHO/EXIT не отображается (тест GalleryImage Функция обратного вызова события prePersist/preUpdate с именем preUpload не срабатывает!)
Мои новые изображения не сохраняются в базе данных? Почему?
Что странно!Если я это сделаю:
Добавление (загрузка) f iles
$em->persist($album)
$em->flush()
снова $em->flush()
Показан мой тест ECHO/EXIT (событие prePersist/preUpdate в GalleryImage Запускается функция обратного вызова с именем preUpload!)
(если я удалю эхо/выход) Теперь мои новые изображения из галереи сохранены!!!
Почему?
Почему 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; } }