123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- <?php
- namespace App\Repository;
- use App\Entity\Product;
- use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
- use Symfony\Bridge\Doctrine\RegistryInterface;
- class ProductRepository extends ServiceEntityRepository
- {
- public function __construct(RegistryInterface $registry)
- {
- parent::__construct($registry, Product::class);
- }
- public function findProductsLessThanQB(float $price)
- {
- $query = $this->createQueryBuilder('p')
- ->andWhere('p.price < :price')
- ->setParameter('price', $price)
- ->orderBy('p.price', 'ASC')
- // ->setMaxResults(10)
- ->getQuery();
- return $query->getResult();
- // to get just one result:
- // $product = $qb->setMaxResults(1)->getOneOrNullResult();
- }
- public function findProductsLessThanDQL(float $price)
- {
- $em = $this->getEntityManager();
- $query = $em->createQuery(
- /** @lang DQL */'
- SELECT p
- FROM App\Entity\Product p
- WHERE p.price < :price
- ORDER BY p.price ASC
- ')->setParameter('price', $price);
- // returns an array of Product objects
- return $query->execute();
- }
- public function findProductsLessThanSQL(float $price) {
- $conn = $this->getEntityManager()->getConnection();
- // With SELECT * we would get category_id, which is not returned by the
- // other queries, as it is a physical DB field, not an entity field.
- $sql = <<<SQL
- SELECT p.description, p.id, p.name, p.price
- FROM product p
- WHERE p.price < :price
- ORDER BY p.price ASC;
- SQL;
- $stmt = $conn->prepare($sql);
- $stmt->execute(['price' => $price]);
- // returns an array of arrays (i.e. a raw data set).
- return $stmt->fetchAll(\PDO::FETCH_CLASS, Product::class);
- }
- public function findOneByIdJoinedToCategory($productId) {
- return $this->createQueryBuilder('p')
- ->innerJoin('p.category', 'c')
- ->addSelect('c')
- ->andWhere('p.id = :id')
- ->setParameter('id', $productId)
- ->getQuery()
- ->getOneOrNullResult();
- }
- }
|