我目前正在使用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类:
<?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
尝试了此ScoRpion中的所有解决方案这里的问题是什么?
答案 0 :(得分:3)
看看这个:
$posts = $em->getRepository('BlogBundle:Post')
->getLatestPosts();
一定是
$posts = $em->getRepository('BlogBlogBundle:Post')
->getLatestPosts();
查找你的命名空间。
答案 1 :(得分:2)
从Entity类注释中删除Repository的完整路径对我有用:
@ORM\Entity(repositoryClass="AdvertRepository")
我不明白为什么......
答案 2 :(得分:1)
对我来说,解决方案是只放置存储库的名称,而没有完整的路径。
是(错误):
* @ORM\Entity(repositoryClass="OC\PlatformBundle\Repository\AdvertRepository")
应该(工作):
* @ORM\Entity(repositoryClass="AdvertRepository")
答案 3 :(得分:-2)
解决方案是将存储库类放在Post Entity旁边的Entity目录中,这就是Entity类:
<?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;
...
...