How to get partial result from doctrine query builder

心已入冬 提交于 2019-12-01 00:00:39

Try something like this, if it's a one to many, the normal mySQL behaviour is returning several records with redundant product data, if the same case happens here, then only returning the first record should do the trick.

PS: assuming the ProductPicture entity has a url property that you want to get

$query = $em->createQueryBuilder()->select('p.id, p.name, pictures.url')
            ->from("SiteMainBundle:Product", 'p')
            ->innerJoin('p.category', 'c')
            ->innerJoin('p.shop', 'shop')
            ->innerJoin('p.pictures', 'pictures')
            ;
Adam Elsodaney

Add a custom repository method with the DQL for your entity, then call it from the controller

You can name the repository method whatever you want, for this example I'm using findProductWithPicture

class ProductRepository extends EntityRepository
{
    /**
     * @param integer $id
     */
    public function findProductWithPicture($id)
    {
        $dql = <<<SQL
SELECT
    p.id    id,
    p.name  name,
    q       picture
FROM
    Shopious\MainBundle\Entity\ProductPicture q,
    Shopious\MainBundle\Entity\Product p
WHERE
    p.id        = :picture_id  AND
    q.product   = p.id
SQL;

        $query = $this->_em->createQuery($dql)->setParameter('picture_id', $id);

        return $query->setMaxResults(1)->getResult();
    }
}

To use this from the controller

$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('ShopiousMainBundle:Product')->findProductWithPicture($id);

return $this->render('ShopiousMainBundle:Product:show.html.twig', array(
    'product' => $product[0]
));

In the rendered Twig template, you can access them like so

<p>{{ product.id }}
<p>{{ product.name }}
<p>{{ product.picture.whatever_property }}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!