Carlos
Carlos

Reputation: 352

symfony 3.1 repository method confusion

I have a repository with this method:

public function getCountryId($code_2a)
{
    return $this
        ->createQueryBuilder('e')
        ->andWhere('e.code2a = :code_2a')
        ->setParameter('code_2a', $code_2a)
        ->getQuery()
        ->execute();
}

and a controller with this call:

$country = $em->getRepository('AppBundle:Countries')->getCountryId('GB');

As I understand in $country I will have an entity with the data of the record of the table, 'Great Britain' in this case.

But if in the controller I do:

$country_id = $country->getId();

I get an exception:

Error: Call to a member function getId() on array 

And this confuses me. How can I get the $id of the country?

Upvotes: 1

Views: 62

Answers (2)

Maxi Schvindt
Maxi Schvindt

Reputation: 1462

In the controller

$country = $em->getRepository('AppBundle:Countries')->findOneByCode2a('GB');
if($country) {
    $country_id = $country->getId();
}

Return one object Country. If you use findBy, return array with objects.

Upvotes: 0

Goku
Goku

Reputation: 2139

Your query return an array which contains object(s) so if you're expecting to receive only one object you have to change your query using getOneOrNullResult

public function getCountryId( $code_2a )
{
    return $this
        ->createQueryBuilder('e')
        ->andWhere('e.code2a = :code_2a')
        ->setParameter('code_2a', $code_2a)
        ->getQuery()
        ->getOneOrNullResult()
    ;
}

Upvotes: 4

Related Questions