Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 825
Cholesterol Avatar asked Aug 17 '26 12:08

Cholesterol


1 Answers

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;
}
like image 120
Tomas Votruba Avatar answered Aug 20 '26 12:08

Tomas Votruba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!