symfony2“Doctrine \ ORM \ EntityRepository”的类子类不是有效实体或映射超类

时间:2013-04-23 09:04:00

标签: symfony doctrine

namespace griffin\UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
/**
 * @ORM\Entity(repositoryClass="griffin\UserBundle\Entity\UserRepository")
 * @ORM\Table(name="users")
 */
class User {

    const STATUS_ACTIVE   = 1;
    const STATUS_INACTIVE = 0;

    /**
     * @ORM\Id
     * @ORM\Column(name="id_users", type="smallint")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $idUsers;

和Repository类一样

namespace griffin\UserBundle\Entity;
use Doctrine\ORM\EntityRepository;

class UserRepository extends EntityRepository {

    public function getAdmin()
    {
        return $this->getEntityManager()
                ->createQuery('select * from users where users_groups_id = 1')
                ->getResults;
    }
}

当我在控制器中调用它时

$results = $this->getDoctrine()
    ->getRepository('griffin\UserBundle\Entity\UserRepository')
    ->getAdmin();

var_dump($results);

我收到了错误 Class "griffin\UserBundle\Entity\UserRepository" sub class of "Doctrine\ORM\EntityRepository" is not a valid entity or mapped super class.

2 个答案:

答案 0 :(得分:12)

getRepository()将实体类作为第一个参数:

$results = $this->getDoctrine()
    ->getRepository('griffin\UserBundle\Entity\User')
    ->getAdmin();

注意:快速查看EntityManager类本身总是一个好主意。如果您这样做,您将看到getRepository()的此方法签名:

/**
 * Gets the repository for an entity class.
 *
 * @param string $entityName The name of the entity.
 *
 * @return EntityRepository The repository class.
 */
public function getRepository($entityName)
{
    //...
}

答案 1 :(得分:1)

请改用$this->getDoctrine->getRepository('griffin\UserBundle\Entity\User')。方法getRepository需要您想要存储库的实体的名称,而不是存储库名称本身,因为并非每个实体都必须具有自定义存储库类。

请参阅http://symfony.com/doc/master/book/doctrine.html#custom-repository-classes