I have one entity Photo and another PhotoNote ( 0 to 10 ) A photo can have note but can’t too
When I request a photo entity I get the following error
Entity of type 'App\Entity\PhotoNote' for IDs idPhoto(1737) was not found
Using this in my controller
$photo = $photoRepository->findOneBy(['idPhoto' => $idPhoto]);
// check if there is a note
$note = (null !== $photo->getPhotoNote() ? $photo->getPhotoNote()->getNotePhoto() : 0);
// Also tried following
//$note = (null !== $photo->getPhotoNote()->getNotePhoto() ? $photo->getPhotoNote()->getNotePhoto() : null);
/**
* --> this throws the error : $photo->getPhotoNote()->getNotePhoto()
*/
And here is the dumping of $photo->getPhotoNote()
in App\Entity\Photo :
Photo.php on line 443:
Proxies\__CG__\App\Entity\PhotoNote {#5710 ▼
+__isInitialized__: false
-idPhoto: 1737
-notePhoto: null
…2
}
Actually $photo->getPhotoNote()
is not null, and photoNote is populated with the photoId. When using $photo->getPhotoNote()->getNotePhoto()
doctrine generates the query to get the associated note, but that photo doesn’t have a note. Note is not mandatory.
What I want is ‘getPhotoNote’ returns null
or even 0
but seems that one to one relation requires an existing id.
How to say to doctrine returns null ?
Class Photo {
/**
* @var int
*
* @ORM\Column(name="id_photo", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $idPhoto.
// some fields
/**
* @ORM\OneToOne(targetEntity=“App\Entity\PhotoNote”)
* @ORM\JoinColumn(name="id_photo", referencedColumnName="id_photo", nullable=true)
*/
private $photoNote;
public function setPhotoNote(PhotoNote $photoNote = null)
{
$this->photoNote = $photoNote;
return $this;
}
public function getPhotoNote()
{
return $this->photoNote;
}
}
Class PhotoNote {
/**
* @ORM\Id()
* @ORM\Column(name="id_photo", type="integer")
*/
private $idPhoto;
/**
* @ORM\Column(name="note_photo", type="smallint")
*/
private $notePhoto;
public function getNotePhoto(): ?int
{
return $this->notePhoto;
}
public function setNotePhoto(int $notePhoto): self
{
$this->notePhoto = $notePhoto;
return $this;
}
}
Generated query :
SELECT
t0.id_photo AS id_photo_1,
t0.note_photo AS note_photo_2
FROM
photo_note t0
WHERE
t0.id_photo = 1737;