symfony2中的自定义存储库类 [英] custom repository class in symfony2
问题描述
我是symfony2的新手,通过命令行创建实体类时创建了一个存储库类,但无法访问该存储库类中的自定义函数.如何在symfony2中创建自定义存储库类?有人可以从头开始为我提供一些示例代码的逐步说明吗?
I'm new in symfony2.I created a repository class when I created an entity class through command line.But I couldn't access my custom functions in that repository class. how to create custom repository class in symfony2? Can anybody give me a step by step explanation from scratch with some sample code?
下面是我的存储库类
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();
}
}
我以这种方式在控制器中打电话
I called in my controller like this way
$em = $this->getDoctrine()->getEntityManager();
$pro = $em->getRepository('symBundle:Register')
->findAllOrderedByName();
我遇到了以下错误
Undefined method 'findAllOrderedByName'. The method name must start with either findBy or findOneBy!
我的代码中是否有任何错误?创建存储库类时有任何错误?我需要使用任何课程吗?
Do I have any mistake in my code ? Any mistake in creating repository class? did i need to use any class.
推荐答案
我认为您只是忘记了在您的实体中注册此存储库. 您只需在实体配置文件中添加存储库类.
I think you just forgot to register this repository in your entity. You just have to add in your entity configuration file the repository class.
在src/Mypro/symBundle/Resources/config/doctrine/Register.orm.yml中:
In src/Mypro/symBundle/Resources/config/doctrine/Register.orm.yml:
Mypro\symBundle\Entity\Register:
type: entity
repositoryClass: Mypro\symBundle\Entity\RegisterRepository
为了以防万一,别忘了在此更改后清除缓存.
Don't forget to clear your cache after this change, just in case.
如果您使用的是Annotations(而不是yml config),请添加以下内容:
And if you're using Annotations (instead of yml config) then instead of the above, add something like:
/**
* @ORM\Entity(repositoryClass="Mypro\symBundle\Entity\RegisterRepository")
*/
进入您的Entity类以注册存储库
to your Entity class to register the repository
这篇关于symfony2中的自定义存储库类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!