ProductRepository.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace App\Repository;
  3. use App\Entity\Product;
  4. use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
  5. use Symfony\Bridge\Doctrine\RegistryInterface;
  6. class ProductRepository extends ServiceEntityRepository
  7. {
  8. public function __construct(RegistryInterface $registry)
  9. {
  10. parent::__construct($registry, Product::class);
  11. }
  12. public function findProductsLessThanQB(float $price)
  13. {
  14. $query = $this->createQueryBuilder('p')
  15. ->andWhere('p.price < :price')
  16. ->setParameter('price', $price)
  17. ->orderBy('p.price', 'ASC')
  18. // ->setMaxResults(10)
  19. ->getQuery();
  20. return $query->getResult();
  21. // to get just one result:
  22. // $product = $qb->setMaxResults(1)->getOneOrNullResult();
  23. }
  24. public function findProductsLessThanDQL(float $price)
  25. {
  26. $em = $this->getEntityManager();
  27. $query = $em->createQuery(
  28. /** @lang DQL */'
  29. SELECT p
  30. FROM App\Entity\Product p
  31. WHERE p.price < :price
  32. ORDER BY p.price ASC
  33. ')->setParameter('price', $price);
  34. // returns an array of Product objects
  35. return $query->execute();
  36. }
  37. public function findProductsLessThanSQL(float $price) {
  38. $conn = $this->getEntityManager()->getConnection();
  39. // With SELECT * we would get category_id, which is not returned by the
  40. // other queries, as it is a physical DB field, not an entity field.
  41. $sql = <<<SQL
  42. SELECT p.description, p.id, p.name, p.price
  43. FROM product p
  44. WHERE p.price < :price
  45. ORDER BY p.price ASC;
  46. SQL;
  47. $stmt = $conn->prepare($sql);
  48. $stmt->execute(['price' => $price]);
  49. // returns an array of arrays (i.e. a raw data set).
  50. return $stmt->fetchAll(\PDO::FETCH_CLASS, Product::class);
  51. }
  52. public function findOneByIdJoinedToCategory($productId) {
  53. return $this->createQueryBuilder('p')
  54. ->innerJoin('p.category', 'c')
  55. ->addSelect('c')
  56. ->andWhere('p.id = :id')
  57. ->setParameter('id', $productId)
  58. ->getQuery()
  59. ->getOneOrNullResult();
  60. }
  61. }