[英]custom repository class in symfony2
我是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!
我的代碼中有任何錯誤嗎? 創建存儲庫類有什么錯誤嗎? 我需要使用任何課程嗎?
我想你只是忘了在你的實體中注冊這個存儲庫。 您只需在實體配置文件中添加存儲庫類。
在src / Mypro / symBundle / Resources / config / doctrine / Register.orm.yml中:
Mypro\symBundle\Entity\Register:
type: entity
repositoryClass: Mypro\symBundle\Entity\RegisterRepository
不要忘記在此更改后清除緩存,以防萬一。
如果您使用的是Annotations(而不是yml配置),那么請添加以下內容:
/**
* @ORM\Entity(repositoryClass="Mypro\symBundle\Entity\RegisterRepository")
*/
到您的Entity類注冊存儲庫
該手冊有一個很好的分步指南... http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes
當我陷入混亂的配置時,我也失去了很多時間。 我在我的實體中將存儲庫類配置為注釋映射。 映射存在,但存儲庫仍未與實體關聯。 當我將注釋映射(即@ORM \\ Entity(repositoryClass =“Acme \\ DemoBundle \\ Entity \\ UserRepository”))移動到最后一行時,它工作正常。
/*
* User
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="Acme\DemoBundle\Entity\UserRepository")
*/
class User
{
...
}`
用於映射的xml:更新文件夾Resource / config / doctrine中的xml映射文件,添加repository-class屬性:
<entity name="Ccd\Bundle\FrontendBundle\Entity\UvUpdatePageContent" table="uv_update_page_content" repository-class="Ccd\Bundle\FrontendBundle\Entity\UvUpdatePageContentRepository">
http://doctrine-mongodb-odm.readthedocs.org/en/latest/cookbook/mapping-classes-to-orm-and-odm.html然后更新緩存:
php app/console doctrine:cache:clear-metadata
php app/console cache:clear
首先,您不需要自定義倉庫來執行此操作。您可以在EM getRepository findBy方法中設置order by子句:
//$em - entity manager
//from Doctrine documentation: findBy(criteria(array), order(array), limit, offset)
$result = $em->getRepository('symBundle:Register')->findBy(array(), array('name' => 'ASC'))
我只需按照原生文檔doc查找我選擇的注釋。 例如,我選擇了yaml,為Product.orm.yml和Category.orm.yml文件添加了配置,還為實體方法添加了新的php屬性:
protected $products;
public function __construct()
{
$this->products = new ArrayCollection();
}
對於Category.php和
protected $category;
對於Product.php
然后運行php app/console doctrine:generate:entities Acme
,成功添加新的getter和setter
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.