Symfony2 未定义的方法。方法名称必须以 findBy 或 findOneBy 开头

Symfony2 Undefined method. The method name must start with either findBy or findOneBy

我目前正在使用 Symfony2 的 Part 4 OF The SymBlog project 我收到此错误消息:

Undefined method 'getLatestPosts'. The method name must start with either findBy 
or findOneBy!500 Internal Server Error - BadMethodCallException

这是我的 PostRepository Class:

    <?php

namespace BLog\BlogBundle\Entity; use Doctrine\ORM\EntityRepository;

class PostRepository extends EntityRepository {

    public function getLatestPosts($limit = null) {
        $qp = $this->createQueryBuilder('p')
                ->select('p')
                ->addOrderBy('p.created', 'DESC');

        if (false === is_null($limit)) {
            $qp->setMaxResults($limit);
        }


        return $qp->getQuery()
                        ->getResult();
    }

}

这是Controller的页面Action方法:

<?php

namespace Blog\BlogBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller {

    public function indexAction() {
        $em = $this->getDoctrine()
                ->getEntityManager();

        $posts = $em->getRepository('BlogBundle:Post')
                ->getLatestPosts();

        return $this->render('BlogBundle:Default:home.html.twig', > >array(
                    'posts' => $posts
        ));
    }
...
}

这是我的 ../../../Entity/Post 代码示例:

<?php

namespace Blog\BlogBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity(repositoryClass="Blog\BlogBundle\Entity\PostRepository")
 * @ORM\Table(name="post")
 * @ORM\HasLifecycleCallbacks
 */

class Post {


....
...
..
/**
     * @ORM\Column(type="text")
     */
    protected $post;
...
...

我也尝试了这个post by ScoRpion

中的所有解决方案

这里的问题是什么???

看看这个:

$posts = $em->getRepository('BlogBundle:Post')
                ->getLatestPosts();

一定是

$posts = $em->getRepository('BlogBlogBundle:Post')
                ->getLatestPosts();

查找您的命名空间。

解决方案是将存储库 class 放在 Post 实体旁边的实体目录中,这是现在的实体 class:

<?php

namespace Blog\BlogBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity(repositoryClass="PostRepository")
 * @ORM\Table(name="post")
 * @ORM\HasLifecycleCallbacks
 */

class Post {


....
...
..
/**
     * @ORM\Column(type="text")
     */
    protected $post;
...
...

对我来说,解决方案是只输入存储库的名称,而不是它的完整路径。

是(错误):

* @ORM\Entity(repositoryClass="OC\PlatformBundle\Repository\AdvertRepository")

应该是(工作):

* @ORM\Entity(repositoryClass="AdvertRepository")

从实体 class 注释中删除存储库的完整路径对我有用: @ORM\Entity(repositoryClass="AdvertRepository")
我不明白为什么...