I use Doctrine with Symfony and I have the following simple Entity:
/**
* @ORM\Table()
*/
class Ads{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var Photo
*
* @ORM\OneToMany(targetEntity="AppBundle\Entity\Photo", mappedBy="advertisement", cascade={"persist", "remove"})
*
*/
private $photos;
/**
* @var string
*/
private $defaultPhoto = null;
public function __construct()
{
$this->photos = new ArrayCollection();
}
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @return ArrayCollection
*/
public function getPhotos()
{
return $this->photos;
}
/**
* @param ArrayCollection $photos
* @return $this
*/
public function setPhotos($photos)
{
$this->photos = $photos;
return $this;
}
public function getDefaultPhoto()
{
if(count($this->getPhotos()) > 0){
return $this->getPhotos()[0];
}
return null;
}
}
So the Entity is a simple one and also has a non persistent field $defaultPhotos
.
My question is how, when I query find
or findAll
with doctrine in Symfony automatically triggers the getDefaultPhoto
method and populate $defaultPhoto
property? Now every time defaultPhoto
is null
when I query find
or findAll
in whole collection.
Is there an event to do that or any other solution?
First, you will not populate anything ($defaultPhoto
) with a getter (getDefaultPhoto
). You can populate defaultPhoto
property on the class' constructor, and then return $this->defaultPhoto
instead of null
on getDefaultPhoto()
method.