无法在Symfony2中调用自定义存储库功能

Kai*_*aja 1 php orm symfony

我们在Symfony2项目中从控制器调用某个自定义实体存储库函数时遇到问题.我们之前已经成功地与其他实体一起完成了它,所以我们可能会遗漏一些东西而且我无法弄清楚它可能是什么.

我们的存储库类如下所示:

<?php

namespace OurSite\Bundle\OurBundle\Entity;
use Doctrine\ORM\EntityRepository;

class BlogRepository extends EntityRepository
{
    public function findPreviousPosts($limit = 6)
    {

        $q = $this->createQueryBuilder('q')
            ->where('q.category = :category')            
            ->setMaxResults($limit)                                                           
            ->add('orderBy', 'q.published ASC')
            ->getQuery();
        $res = $q->getResult();
        return $res;
    }
}
Run Code Online (Sandbox Code Playgroud)

实体:

<?php

namespace OurSite\Bundle\OurBundle\Entity;

use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;

/**
* OurSite\Bundle\OurBundle\Entity\Blog
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="OurSite\Bundle\OurBundle\Entity\BlogRepository")
*/
class Blog {
    // Non-relevant stuff here
}
Run Code Online (Sandbox Code Playgroud)

当我们调用这样的方法时:

$em = $this->getDoctrine()->getEntityManager();
$previousPosts = $em->getRepository('OurSiteOurBundle:Blog')->findPreviousPosts();
Run Code Online (Sandbox Code Playgroud)

我们得到这个:

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

如果我们按预期进行echo get_class($em->getRepository('OurSiteOurBundle:Blog'));输出BlogRepository.

可能导致问题的原因是什么?我们bundle在项目中有一个多余的目录,但我猜这不会导致它?

tar*_*ion 6

从您提供的来源,这可能不是您的问题,但它可以节省其他一些搜索时间.

我遇到了同样的问题"必须从findBy或者......开始"错误,结果在我的实体定义中我不小心调用了@ORM\Entity注释两次.我第一次正确使用它并设置repositoryClass,但第二次我只是单独使用它(与没有自定义存储库的实体一样),因此覆盖了以前的repositoryClass定义.

 /**
 *
 * @ORM\Entity(repositoryClass="Company\TestBundle\Entity\MyEntityRepository")
 * @ORM\Table(name="testing_my_entity")
 * @ORM\Entity
 */

class MyEntity
{
etc...
}
Run Code Online (Sandbox Code Playgroud)