How to get partial result from doctrine query builder

后端 未结 2 1524
太阳男子
太阳男子 2021-01-06 22:41

I have a product entity in which it has an array as attributes:

     /**
     * @ORM\\OneToMany(targetEntity=\"Shopious\\MainBundle\\Entity\\ProductPicture\"         


        
2条回答
  •  旧巷少年郎
    2021-01-06 23:02

    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 = <<_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

    {{ product.id }}

    {{ product.name }}

    {{ product.picture.whatever_property }}

提交回复
热议问题