فهرست منبع

ORM: querying with the QueryBuilder on the entity repository.

Frederic G. MARAND 6 سال پیش
والد
کامیت
f1d45114c9
2فایلهای تغییر یافته به همراه13 افزوده شده و 18 حذف شده
  1. 4 8
      src/Controller/ProductController.php
  2. 9 10
      src/Repository/ProductRepository.php

+ 4 - 8
src/Controller/ProductController.php

@@ -3,6 +3,7 @@
 namespace App\Controller;
 
 use App\Entity\Product;
+use App\Repository\ProductRepository;
 use Doctrine\ORM\EntityManagerInterface;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\Routing\Annotation\Route;
@@ -22,9 +23,9 @@ class ProductController extends Controller
    *
    * @return \Symfony\Component\HttpFoundation\Response
    */
-  public function index(EntityManagerInterface $em) {
-    $repository = $em->getRepository(Product::class);
-    $products = $repository->findAll();
+  public function index(ProductRepository $repository) {
+    // Can also be fetched from the EntityManager, but simpler to inject it.
+    $products = $repository->findProductsLessThan(21);
     return $this->render('product/index.html.twig', ['products' => $products]);
   }
 
@@ -82,11 +83,6 @@ class ProductController extends Controller
       return $accu . '/' .  $product->getId() . ' ' . $product->getName() . ': ' . $product->getDescription();
     }, ''));
 
-    $productsAll = $repository->findAll();
-    $this->addFlash('error', array_reduce($productsAll, function (string $accu, Product $product) {
-      return $accu . '/' .  $product->getId() . ' ' . $product->getName() . ': ' . $product->getDescription();
-    }, ''));
-
     if (!$product) {
       throw $this->createNotFoundException(
         "No product found for id $id"

+ 9 - 10
src/Repository/ProductRepository.php

@@ -13,16 +13,15 @@ class ProductRepository extends ServiceEntityRepository
         parent::__construct($registry, Product::class);
     }
 
-    /*
-    public function findBySomething($value)
+    public function findProductsLessThan($price)
     {
-        return $this->createQueryBuilder('p')
-            ->where('p.something = :value')->setParameter('value', $value)
-            ->orderBy('p.id', 'ASC')
-            ->setMaxResults(10)
-            ->getQuery()
-            ->getResult()
-        ;
+        $qb = $this->createQueryBuilder('p')
+          ->andWhere('p.price < :price')
+          ->setParameter('price', $price)
+          ->orderBy('p.price', 'ASC')
+          // ->setMaxResults(10)
+          ->getQuery();
+
+        return $qb->getResult();
     }
-    */
 }