Search code examples
symfonydoctrineentitylazy-loading

retrieve attribute from object in entity doctrine


So I have this function :

MyProject\Bundle\Entity\Audio;

/**
 * 
 * @return string
 */ 
public function getStudioName()
{
   return $this->getStudio()->getNom();
}

which is supposed to retrieve the attribute nom from the object Studio.

They are defined like this :

/**
 * @var \MyProject\Bundle\Entity\Device
 */

private $studio;

...

/**
 * Get studio
 *
 * @return \MyProject\Bundle\Entity\Device
 */
public function getStudio()
{
    return $this->studio;
}

And the ->getNom is just also a basic return, which works fine.

So i get that following error message :

Error: Call to a member function getNom() on a non-object

I've read about lazy loading and I understand why $this->getStudio() gives me a proxy instead of an actual Device object, but I can't go further and use getNom() after that... I've tried to add fetch : EAGER to avoid lazy loading but it still doesn't work.

Any ideas ?


Solution

  • It looks like property $studio can be NULL. In such a case, you need to validate if it is set. If not, return NULL.

    The real code would look like this:

    <?php 
    
    public function getStudioName(): ?string
    {
        return $this->studio ? $this->studio->getName() : null;
    }