phpsymfonydoctrinedql

can't get result object in doctrine


I got DQL like this:

$sql =$qb->select('login,id')
->from('Cusomter','c')
->where('c.login = :login')
->setParameter('login',$login);
$rs = $sql->getQuery()->getResult();

I want the result would return as object with 2 properties: Login,id. Is there anyway i can do that? I tried CustomHydrator but it won't work out. this is my CustomHydrator:

namespace Hydrator;

use Doctrine\ORM\Internal\Hydration\AbstractHydrator;

class CustomHydrator extends AbstractHydrator
{
   protected function hydrateAllData()
   {
    return $this->_stmt->fetchAll(\PDO::FETCH_ASSOC);
   }
}

Then i added $em->getConfiguration()->addCustomHydrationMode('CustomHydrator', 'Hydrator\CustomHydrator');
and run :$rs = $sql->getQuery()->getResult('CustomHydrator');


Solution

  • There are a few ways to go about this. If this is a query that you need to reuse, then Doctrine custom hydrators is perhaps the best approach. If not, you could simply cast the result to an object.

    If you need a single result:

    $sql =$qb->select('c.login, c.id')
        ->from('Cusomter','c')
        ->where('c.login = :login')
        ->setParameter('login', $login);
    $rs = (object) $sql->getQuery()->getSingleResult();
    

    If you need to return an array of objects (i.e. multiple result items), then you could just cast each result:

    $sql =$qb->select('c.login, c.id')
        ->from('Cusomter','c')
        ->where('c.login = :login')
        ->setParameter('login', $login);
    
    $rs_new = array_map(function ($value) {
        return (object) $value;
    }, $sql->getQuery()->getResult());