symfony2 中的自定义存储库类

2022-08-30 14:26:26

我是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();
    }


}

我以这种方式调用我的控制器

$em = $this->getDoctrine()->getEntityManager();
          $pro = $em->getRepository('symBundle:Register')
            ->findAllOrderedByName();

我收到以下错误

Undefined method 'findAllOrderedByName'. The method name must start with either findBy or findOneBy!

我的代码中是否有任何错误?创建存储库类时有任何错误吗?我需要使用任何类。


答案 1

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

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

Mypro\symBundle\Entity\Register:
    type: entity
    repositoryClass: Mypro\symBundle\Entity\RegisterRepository

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

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

/**
 * @ORM\Entity(repositoryClass="Mypro\symBundle\Entity\RegisterRepository")
*/

到实体类以注册存储库


答案 2

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

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

推荐