Symfony 4, doctrine, getResult and getArrayResult and getScalarResult return same structure results

11,306

I might be late but for further notice, I think the right answer is described here.

You can use getScalarResult() then use array_column like that:

$emailArray = array_column($getScalarResult(), "email");
Share:
11,306

Related videos on Youtube

spacecodeur
Author by

spacecodeur

Updated on May 25, 2022

Comments

  • spacecodeur
    spacecodeur almost 2 years

    From symfony 4, I create a sample repository class. From this class, I created a method for get the list of all email's users. I would like get a array structure like this :

    array(
        "email1",
        "email2",
        "email3",
        ...       
    )
    

    But with 'getResult' I get a multidimensional array. Then, I tested with getArrayResult and getScalarResult and I obtain each time exactly the same array structure result !

    Below, my Service Class :

    <?php
    class UserRepository extends ServiceEntityRepository
    {
        public function __construct(RegistryInterface $registry)
        {
            parent::__construct($registry, User::class);
        }
    
        public function getAllEmail(){
            $result = $this->createQueryBuilder('u')
                ->select(array('u.email'))
                ->setMaxResults(5)
                ->getQuery();
            return array( // getResult && getArrayResult && getScalarResult return exactly same array structure
                "getResult" => $result->getResult(),
                "getArrayResult" => $result->getArrayResult(), 
                "getScalarResult" => $result->getScalarResult(),
            );
        }
    }
    

    And the result when I dump the output of "getAllEmail()" :

    enter image description here

    Why getResult / getArrayResult / getScalarResult return exactly same array structure ? I do a mistake somewhere ?

    Edit : I modified my Repository Class :

    public function getAllEmail(){
        $result = $this->createQueryBuilder('u','u.email')
            ->setMaxResults(5)
            ->getQuery();
        return array(
            "getResult" => $result->getResult(),
            "getArrayResult" => $result->getArrayResult(),
            "getScalarResult" => $result->getScalarResult(),
        );
    }
    

    And the dump output :

    enter image description here

    With 'getResult' and 'getArrayResult' I get an multidimensional array and in the first dimension, I get all email (emails are the key). I approach more my goal but its not perfect. I'm looking for the 'light weight' way (sorry for my english -_-), I would like get only email (and not email + another useless users information) because I want execute the simplest query as possible. Is it possible ?

  • spacecodeur
    spacecodeur over 6 years
    Thanks for your answer, I modifiy my method. I get differnt results, but I haven't a simple one dimensional array