0

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!

David Patterson
  • 1,780
  • 3
  • 17
  • 40
  • Could you cite something or share some code? I have functions in Doctrine repositories that do not start with `find` or `count`. – ficuscr Jul 03 '19 at 19:56
  • @ficusr, Sure. Please see the edit to my original post. Thanks. – David Patterson Jul 03 '19 at 20:08
  • 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 Jul 03 '19 at 20:15
  • 2
    [The method name must start with either findBy or findOneBy. Undefined method Symfony?](https://stackoverflow.com/questions/9172586/the-method-name-must-start-with-either-findby-or-findoneby-undefined-method-sym) might be helpful. – ficuscr Jul 03 '19 at 20:17

1 Answers1

0

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).

David Patterson
  • 1,780
  • 3
  • 17
  • 40