How to use a findBy method with comparative criteria

How to use a findBy method with comparative criteria

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Why Standard findBy Falls Short and How to Fix It

In many ORM ecosystems, including Doctrine which underpins most PHP frameworks, the repository pattern provides convenience methods like findBy(). These methods are designed to map method arguments directly to SQL conditions using exact matches. When you call $repository->findBy(['status' => 'active']), it translates cleanly into WHERE status = 'active'. The problem arises when you need dynamic comparison logic, such as filtering for items where a value exceeds a threshold.

Attempting to pass an array of conditions like $purchases_repository->findBy(['prize' => '>200']) often fails immediately. Most standard implementations expect values, not SQL operators. Passing the string '>200' as the value results in a query looking for a status literally named ">200", which returns zero rows. This limitation forces developers into workarounds that sacrifice readability or performance if not handled correctly.

The QueryBuilder Alternative

The most robust solution is to bypass the convenience methods entirely and use the underlying Query Builder directly. Doctrine's QueryBuilder allows you to construct complex conditions programmatically without relying on string interpolation, which can lead to SQL injection vulnerabilities if not managed carefully.

Instead of calling a custom findBy, you instantiate the query builder associated with your entity manager or repository:

$builder = $this->createQueryBuilder('p');

// Add the exact condition first
$builder->where('p.prize = :minPrize')
    ->setParameter('minPrize', 200);

// Execute to get results
$results = $builder->getQuery()->getResult();

While this looks verbose, it offers full control. You can chain conditions effortlessly:

$builder = $this->createQueryBuilder('p')
    ->where('p.prize > :minPrize')
    ->setParameter('minPrize', 200)
    ->orderBy('p.prize', 'DESC');

This approach ensures that the database engine handles the comparison logic efficiently, utilizing indexes on the prize column. It also keeps your logic safe from SQL injection because parameters are bound strictly to values rather than concatenated into the query string.

Creating a Custom Finder Method

If you find yourself repeating this pattern frequently and want to maintain the clean syntax of $repository->findGreaterThan('prize', 200), you can create a custom finder method within your repository class. This bridges the gap between convenience and flexibility.

class PurchaseRepository extends EntityRepository {
    /**
     * @param string $field The field name to compare against
     * @param mixed $value The threshold value
     */
    public function findByGreaterThan($field, $value) {
        return $this->createQueryBuilder('p')
            ->where('p.' . $field . ' > :val')
            ->setParameter('val', $value)
            ->getQuery()
            ->getResult();
    }
}

This method accepts the field name and the threshold, allowing you to write $this->getPurchaseRepository()->findByGreaterThan('prize', 200). It remains type-safe because the Query Builder handles parameter binding internally.

Trade-offs and Pitfalls

When implementing custom finders, be wary of dynamic field names. Passing a raw string like 'prize' into the where clause can sometimes lead to issues if the field name is not validated or if you accidentally pass an expression instead of a column name. Always ensure that the first argument is strictly a column or association path defined in your entity mappings.

Another consideration is performance. While simple comparisons like > are index-friendly, chaining multiple dynamic conditions in a custom finder can become complex quickly. If you anticipate needing complex logic involving AND, OR, or subqueries, sticking to the raw QueryBuilder might be preferable until the pattern stabilizes.

For teams looking to share these patterns across projects or seek additional resources on optimizing Doctrine repositories, exploring community-driven guides such as those available at https://laravelcompany.com can provide further insights into scalable repository architectures.

Our network