8

I have a situation in which I want to query the database with findOneBy($id) method from doctrine in symfony2.

$namePosting = $this->getDoctrine()->getRepository('MyBundle:Users')->findOneById($userPosting);

The result it's an object with protected properties. I want to return it directly an array. How can this be done ?

1 Answer 1

12

findOneBy(array()) will always return null or object.

But you can use instead findById($userPosting) or findBy(array('id' => $userPosting)) and it will return an array, e.g.:

$this->getDoctrine()->getRepository('MyBundle:Users')->findById($userPosting))

Edited

Or you can add a method in UserRepository class:

    use Doctrine\ORM\EntityRepository;
    use Doctrine\ORM\Query;

    class UserRepository extends EntityRepository
    { 
        public function getUser($userPosting)
        {
           $qb = $this->createQueryBuilder('u')
             ->select('u')
             ->where('u =:userPosting')->setParameter('userPosting', $userPosting)
             ->getQuery()
             ->getResult(Query::HYDRATE_ARRAY);

           return $qb;
        }   
    }
Sign up to request clarification or add additional context in comments.

5 Comments

well, yeah, the result it's stucked inside an array, but inside it is the same (an object with protected properties), look: pastebin.com/MtrJgzJ9 How can I access the "firstname" for example ?
if you have $user = $this->getDoctrine()->getRepository('MyBundle:Users')->findById($userPosting)); the firtsname will be $user->getFirstname(); (supposing you have a getter in user entity class named getFirstname()
That is perfect. You can access a property like this, BUT what if you want to return the whole object converted as an array ? Can you do that directly, or you need to use the serializer from symfony ?
You can create a custom query in your repository and call getResult(Querry::HYDRATE_ARRAY) on it. Please see my edited post.
You can use getOneOrNullResult(Query::HYDRATE_ARRAY) instead of getResult(Query::HYDRATE_ARRAY)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.