비교 기준으로 findBy 메소드를 사용하는 방법
비교 기준 (정확한 기준뿐만 아니라)을 사용하는 "매직 파인더"findBy 메서드를 사용해야합니다. 즉, 다음과 같이해야합니다.
$result = $purchases_repository->findBy(array("prize" => ">200"));
상금이 200 이상인 모든 구매를받을 수 있습니다.
이것은 Expr () 클래스 를 사용하는 예입니다. 며칠 전에 너무 필요했고 정확한 구문과 사용 방법이 무엇인지 알아내는 데 약간의 시간이 걸렸습니다.
/**
* fetches Products that are more expansive than the given price
*
* @param int $price
* @return array
*/
public function findProductsExpensiveThan($price)
{
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
$q = $qb->select(array('p'))
->from('YourProductBundle:Product', 'p')
->where(
$qb->expr()->gt('p.price', $price)
)
->orderBy('p.price', 'DESC')
->getQuery();
return $q->getResult();
}
클래스 Doctrine\ORM\EntityRepository
는 Doctrine\Common\Collections\Selectable
API를 구현 합니다.
Selectable
인터페이스는 매우 유연하고 아주 새로운,하지만 ORM 또는 ODM 또는 완전히 별개의 문제의 경우에 관계없이, 저장소 및 항목의 단일 컬렉션 모두에서 쉽게 비교하고 더 복잡한 조건을 처리 할 수 있습니다.
이것은 Doctrine ORM에서와 같이 방금 요청한 비교 기준이 될 것입니다 2.3.2
.
$criteria = new \Doctrine\Common\Collections\Criteria();
$criteria->where($criteria->expr()->gt('prize', 200));
$result = $entityRepository->matching($criteria);
이 API의 가장 큰 장점은 여기에서 일종의 전략 패턴을 구현하고 저장소, 컬렉션, 지연 컬렉션 및 Selectable
API가 구현되는 모든 곳에서 작동한다는 것입니다.
이를 통해 리포지토리에 대해 작성한 수십 개의 특수 메서드 (예 :)를 제거 findOneBySomethingWithParticularRule
하고 대신 이러한 특정 필터 중 하나를 나타내는 자체 기준 클래스를 작성하는 데 집중할 수 있습니다.
DQL 또는 QueryBuilder 를 사용해야합니다 . 예를 들어 Purchase- EntityRepository 에서 다음과 같이 할 수 있습니다.
$q = $this->createQueryBuilder('p')
->where('p.prize > :purchasePrize')
->setParameter('purchasePrize', 200)
->getQuery();
$q->getResult();
더 복잡한 시나리오의 경우 Expr () 클래스를 살펴보십시오 .
Symfony 문서는 이제이를 수행하는 방법을 명시 적으로 보여줍니다.
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT p
FROM AppBundle:Product p
WHERE p.price > :price
ORDER BY p.price ASC'
)->setParameter('price', '19.99');
$products = $query->getResult();
에서 http://symfony.com/doc/2.8/book/doctrine.html#querying-for-objects-with-dql
$criteria = new \Doctrine\Common\Collections\Criteria();
$criteria->where($criteria->expr()->gt('id', 'id'))
->setMaxResults(1)
->orderBy(array("id" => $criteria::DESC));
$results = $articlesRepo->matching($criteria);
참고 URL : https://stackoverflow.com/questions/14786937/how-to-use-a-findby-method-with-comparative-criteria
'development' 카테고리의 다른 글
Python에서 구분 된 줄에 목록 요소 인쇄 (0) | 2020.10.25 |
---|---|
NSIndexpath.item 대 NSIndexpath.row (0) | 2020.10.25 |
파이썬 정규식이 모든 겹치는 일치를 찾으십니까? (0) | 2020.10.25 |
Java에서 두 문자열 세트를 결합하는 더 좋은 방법이 있습니까? (0) | 2020.10.25 |
신속한 변수가있는 NSLocalizedString (0) | 2020.10.25 |