FORSMILE
JA
Symfony2021/07/06

When you encounter 'Error: Call to a member function on array' with data retrieved by findBy [Symfony]

Looking back, it seems obvious, but I'm documenting this as I reviewed it when the error occurred. The error 'Call to a member function on array' happened when trying to get data from an entity retrieved with findBy.

Back to Blog

Looking back, it seems obvious, but I'm documenting this as I reviewed it when the error occurred. The error 'Call to a member function on array' happened when I tried to retrieve data from an entity obtained using `findBy`.

REASON FOR THE ERROR

javascript
// 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 example above will throw an error. The reason is that the Entity retrieved by `findBy` is an array.

Therefore, to directly get data as an Entity, you need to retrieve only a single Entity.

ERROR RESOLUTION

Assuming you want to retrieve a single record, it's fine to get just one Entity instead of an array.

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

This might be obvious to experienced developers, but I stumbled upon it, so I decided to document it.

Recommended Symfony Books

There aren't many varieties, and since the framework itself has a vast amount of information, even introductory books can be quite substantial reads.

📦
Amazon で関連書籍・ツールを検索
Symfony PHP framework book
Amazonで探す →(アソシエイトリンク)