Yusuf Ibrahim
Yusuf Ibrahim

Reputation: 1619

cannot fetch related entity data from findAll()

I get problem when load related data using findAll (I try to load attribute username from related entity) :

$repository = $this->getDoctrine()->getRepository('MyAwesomeBundle:Employee');

$employees = $repository->findAll();
foreach ($employees as $employee) {
    echo $employee->getUser()->getUsername();
}
die("not work -_-"); 

error message : FatalErrorException: Error: Call to a member function getUsername() on a non-object in...

but my other code using findOne is working correctly :

$repository = $this->getDoctrine()->getRepository('MyAwesomeBundle:Employee');
$employee = $repository->findOneByCode($code);
die("".$employee->getUser()->getUsername());

my question is how to load $employee->getUser()->getUsername() inside foreach if I use findAll to load all data ?

Upvotes: 0

Views: 173

Answers (1)

Igor Pantović
Igor Pantović

Reputation: 9246

You have an Employee in database that has no User associated with it.

When loading just one, you are loading one who has User associated, but when looping over all, you stumble upon one who doesn't and at that point, your code fails.

Solution: find Employee without associated User and remove it, or associate a User with it.

Upvotes: 2

Related Questions