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

4

2 回答 2

13

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)
{
    //...
}
于 2013-04-23T09:18:54.717 回答
1

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

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

于 2013-04-23T09:19:14.280 回答