When “Error: Call to a member function on array” appears in the data acquired by findBy [Symfony]

This is an article about Symfony and Doctrine.
Each version of my environment is as follows.
Symfony 3.4
Doctrine 2.12

It’s natural if you think about it later, but I reviewed it when an error occurred, so make a note. “Error: Call to a member function on array” occurs when trying to get data from the entity obtained by findBy.

The reason for the error

Sample that gives an error

// get data where "userId" is testerXX
$userRepository = $entityManager->getRepository('AppBundle:User');
$userEntity = $userRepository->findBy(
    ['userId' => 'testerXX']
);
// Get "name" from the obtained entity
$userEntity->getName();

// Error: Call to a member function on array

The above example will result in an error. The reason is that the Entity acquired by findBy is an array.
So, to get the data as Entity as it is, you need to get only one Entity.

Error resolution method

There is a premise that the data you want to get is one record, but it is OK if you get one Entity instead of an array.
So use findOneBy to get it.

// get data where "userId" is testerXX
$userRepository = $entityManager->getRepository('AppBundle:User');
$userEntity = $userRepository->findOneBy( ['userId' => 'testerXX'] );
// Get "name" from the obtained entity
$userEntity->getName();

It’s a story to those who know that, but I got caught a little, so I summarized it.


Leave a Reply 0

Your email address will not be published.

nineteen + 19 =