Магия Doctrine2 нашла, когда в поле есть подчеркивание? - PullRequest
5 голосов
/ 12 марта 2012

У меня проблемы с использованием find*() магических методов Doctrine2, когда поле имеет подчеркивание между ними.

$repository->findByName("Hello"); // Works
$repository->findByIsEnabled(true);

Entity 'Acme \ SecurityBundle \ Entity\ Package 'не имеет поля' isEnabled '.Поэтому вы не можете вызывать 'findByIsEnabled' в хранилище сущностей.

Это простое определение сущности в YAML для репликации ошибки:

Acme\SecurityBundle\Entity\Package:
  type: entity
  repositoryClass: Acme\SecurityBundle\Repository\PackageRepository
  table: security_package
  id:
    id:
      type: integer
      generator: { strategy: AUTO }
  fields:
    name:
      type: string
      length: 255
      unique: true
    is_enabled:
      type: boolean

1 Ответ

16 голосов
/ 12 марта 2012

Я помню, что у меня была такая же проблема, и думаю, что решил ее, написав что-то вроде этого:

$ repository-> findBy (array ('is_enabled' => true));

Давайте посмотрим на код:

<?php
/**
 * Adds support for magic finders.
 *
 * @return array|object The found entity/entities.
 * @throws BadMethodCallException  If the method called is an invalid find* method
 *                                 or no find* method at all and therefore an invalid
 *                                 method call.
 */
public function __call($method, $arguments)
{   
    if (substr($method, 0, 6) == 'findBy') {
        $by = substr($method, 6, strlen($method));
        $method = 'findBy';
    } else if (substr($method, 0, 9) == 'findOneBy') {
        $by = substr($method, 9, strlen($method));
        $method = 'findOneBy';
    } else {
        throw new \BadMethodCallException(
            "Undefined method '$method'. The method name must start with ".
            "either findBy or findOneBy!"
        );  
    }   

    if ( !isset($arguments[0])) {
        // we dont even want to allow null at this point, because we cannot (yet) transform it into IS NULL.
        throw ORMException::findByRequiresParameter($method.$by);
    }

    $fieldName = lcfirst(\Doctrine\Common\Util\Inflector::classify($by));

    if ($this->_class->hasField($fieldName) || $this->_class->hasAssociation($fieldName)) {
        return $this->$method(array($fieldName => $arguments[0]));
    } else {
        throw ORMException::invalidFindByCall($this->_entityName, $fieldName, $method.$by);
    }
}

Ключевая строка здесь:

$fieldName = lcfirst(\Doctrine\Common\Util\Inflector::classify($by));

Теперь давайте рассмотрим классификацию:

<?php
/**
 * Convert a word in to the format for a Doctrine class name. Converts 'table_name' to 'TableName'
 *
 * @param string  $word  Word to classify
 * @return string $word  Classified word
 */
public static function classify($word)
{
    return str_replace(" ", "", ucwords(strtr($word, "_-", "  ")));
}

Похоже, что вы должны написать свои поля "likeThis", если вы хотите, чтобы это работало.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...