0
votes

I just realize that in symfony if you didn't not mention specific field the doctrine will return you a lot of junk data such as debug time and etc. How can we query all database field with only the field results? Example: SELECT * FROM user WHERE username = 'abc', then it will only return all fields in user table not including those junk data.

$q = $this
     ->createQueryBuilder('u')
     ->where('u.username = :username')
     ->setParameter('username', $username)
     ->getQuery();

try {
    // The Query::getSingleResult() method throws an exception
    // if there is no record matching the criteria.
    $user = $q->getSingleResult();
    var_dump($user);
} catch (NoResultException $e) {
     $user = false;
}

The results of the above code:

enter image description here

I don't need all those data, I only need the fields in the data. Your help is very much appreciated. Thank you.

2

2 Answers

2
votes

You are using var_dump. That is what is annotating the data. There is nothing external in there, but you are dumping a giant object tree. Usually it hangs, so you're lucky you even got anything there.

Use this instead for just getting the raw data:

Doctrine\Common\Util\Debug::dump($user);
1
votes

That is not a junk. It's probably whole Doctrine, since your object has reference to it. Do you want to get rid of Doctrine? Doctrine has many internal mechanisms you don't usually think about, because... well... it's the ORM and not just queries and flat objects.

Only thing you get from database is data you want and doctrine don't perform useless queries.

I think you just don't fully understand how doctrine works. You in fact DO WANT that whole object. It's a point of the Doctrine - to map your database to objects. That is what "ORM" means. It's main feature, not a flaw.


However sometimes you do really want just plain data without all doctrine thing. You can get that. Just change hydration to array (check doctrine docs for more details about what hydration is). Use

$q->getSingleResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);

That also happen by default if you choose only some fields instead of whole object.