Skip to content

Instantly share code, notes, and snippets.

@peterjmit
Created March 4, 2012 14:32
Show Gist options
  • Save peterjmit/1973260 to your computer and use it in GitHub Desktop.
Save peterjmit/1973260 to your computer and use it in GitHub Desktop.
Array hydration Example
<?php
namespace Vendor\Prefix\Repository;
use Doctrine\ORM\EntityRepository;
class ProductRepository extends EntityRepository
{
public function find($id)
{
// $em is the entity manager
$qb = $em->createQueryBuilder();
$qb
->select('product', 'category', 'tag', 'brand')
// Or SomeBundle:Product if you're on symfony
->from('Vendor\Prefix\Entity\Product', 'product')
// You need to explicitly fetch join all your
// associations...and select them
->leftJoin('product.Brand', 'brand')
->leftJoin('product.Tags', 'tag')
->leftJoin('product.Categories', 'category')
// Use prepared statments...its a good habit
->where($qb->expr()->eq('product.ID', ':id'))
->setParameter('id', $id)
;
$query = $qb->getQuery();
// Potential Hydration Modes
// --------------------------------
// Doctrine\ORM\Query::HYDRATE_OBJECT
// Doctrine\ORM\Query::HYDRATE_ARRAY
// Doctrine\ORM\Query::HYDRATE_SCALAR
// Doctrine\ORM\Query::HYDRATE_SINGLE_SCALAR
// Doctrine\ORM\Query::HYDRATE_SIMPLEOBJECT
// Hydrate the result as an array to get the requested format
// When you use array hyrdation doctrine does it according
// to your entity graph
return $query->getResult(Doctrine\ORM\Query::HYDRATE_ARRAY);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment