symfony2中的自定义存储库类

Asi*_* AP 31 php symfony

我是symfony2的新手.当我通过命令行创建实体类时,我创建了一个存储库类.但是我无法访问该存储库类中的自定义函数.如何在symfony2中创建自定义存储库类?有人可以从头开始用一些示例代码给我一步一步的解释吗?

下面是我的存储库类

namespace Mypro\symBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * RegisterRepository
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class RegisterRepository extends EntityRepository
{


    public function findAllOrderedByName()
    {
        return $this->getEntityManager()
            ->createQuery('SELECT p FROM symBundle:Register p ORDER BY p.name ASC')
            ->getResult();
    }


}
Run Code Online (Sandbox Code Playgroud)

我这样打电话给我的控制器

$em = $this->getDoctrine()->getEntityManager();
          $pro = $em->getRepository('symBundle:Register')
            ->findAllOrderedByName();
Run Code Online (Sandbox Code Playgroud)

我得到了以下错误

Undefined method 'findAllOrderedByName'. The method name must start with either findBy or findOneBy!
Run Code Online (Sandbox Code Playgroud)

我的代码中有任何错误吗?创建存储库类有什么错误吗?我需要使用任何课程吗?

Reu*_*ven 69

我想你只是忘了在你的实体中注册这个存储库.您只需在实体配置文件中添加存储库类.

在src/Mypro/symBundle/Resources/config/doctrine/Register.orm.yml中:

Mypro\symBundle\Entity\Register:
    type: entity
    repositoryClass: Mypro\symBundle\Entity\RegisterRepository
Run Code Online (Sandbox Code Playgroud)

不要忘记在此更改后清除缓存,以防万一.

如果您使用的是Annotations(而不是yml配置),那么请添加以下内容:

/**
 * @ORM\Entity(repositoryClass="Mypro\symBundle\Entity\RegisterRepository")
*/
Run Code Online (Sandbox Code Playgroud)

到您的Entity类注册存储库


Man*_*eUK 6

该手册有一个很好的分步指南... http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes

  • 首先在annotations/yaml配置中定义存储库类
  • 创建类
  • 创建功能
  • 然后调用新创建的函数....