0
votes

Can someone please explain to me why Doctrine requires repository method names to start with findBy, findOneBy, or countBy and why even names with those prefixes must end with a column name?

There are valid use cases where it is useful, for example, to count the number of records that contain several matching columns.

// src/Repository/FreeClassQueryRepository.php
class FreeClassQueryRepository extends ServiceEntityRepository
{
  .
  .
  .
  /**
   * Returns true if one or more free class query records match the supplied
   * FreeClassQuery object.
   *
   * @param   FreeClassQuery $query
   * @return  bool
   * @throws  \Doctrine\ORM\NonUniqueResultException
   */
  public function checkForDuplicate( FreeClassQuery $query )
  {
    $q = $this->createQueryBuilder( 'fcq' )
              ->select( 'COUNT(id)' )
              ->andWhere( 'fcq.name = :name' )
              ->setParameter( 'name', $query->getName())
              ->andWhere( 'fcq.email = :email' )
              ->setParameter( 'email', $query->getEmail())
              ->andWhere( 'fcq.street = :street' )
              ->setParameter( 'street', $query->getStreet())
              ->andWhere( 'fcq.city = :city' )
              ->setParameter( 'city', $query->getCity())
              ->andWhere( 'fcq.state = :state' )
              ->setParameter( 'state', $query->getState());
    return $q->getQuery()->getSingleScalarResult();

  }
  .
  .
  .
}

Calling this method results in this error:

[ERROR] app:debug (Prototyping...) failed Undefined method 'checkForDuplicate'. The method name must start with either findBy, findOneBy or countBy!

1
Could you cite something or share some code? I have functions in Doctrine repositories that do not start with find or count.ficuscr
@ficusr, Sure. Please see the edit to my original post. Thanks.David Patterson
OK. So that looks to be magic sauce. The exception is raised in __call - if calling a concrete method of the class that should not happen. So, has more to do with how it's invoked. How do you use checkForDupelicate?ficuscr

1 Answers

0
votes

This was happening because the @ORM\Entity annotation in the entity class was missing the repositoryClass="App\Repository\FreeClassQueryRepository" attribute.

Thanks to @ficuscr for the link to a similar StackOverflow question (see his third comment).