2012-03-11 1 views
4

フィールドの下にのフィールドがある場合、find*()のDoctrine2の魔法の使用で問題が発生しています。フィールドにアンダースコアがある場合、Magic Doctrine2ファインダー?

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

Entity 'Acme\SecurityBundle\Entity\Package' has no field 'isEnabled'. You can therefore not call 'findByIsEnabled' on the entities' repository.

これはエラーを複製するための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 

答えて

16

私は同じ問題を抱えていたと私はこのような何かを書くことで、それを解決したと考えたリコール:

$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を」あなたのフィールドを書くことになっているように見えますこれはうまくいく。

+0

はい私は(回避策として)まったく同じことをやっていますが、私は「魔法」の方が好きです。これはバグですか? – gremo

+0

ドキュメントに例がありますか?私はできません。同様の問題[この他の質問](http://stackoverflow.com/questions/7698874/doctrine2-and-magic-finders-with-more-field-not-working)、おそらく魔法の部分は落胆している。 – greg0ire

+0

はい、Symfonyのドキュメントでは、http://symfony.com/doc/current/book/doctrine.htmlを見てください。 – gremo

関連する問題