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

时间:2015-03-04 10:32:11

标签: php symfony model-view-controller controller doctrine

我目前正在使用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中的所有解决方案

这里的问题是什么?

1 个答案:

答案 0 :(得分:0)

此处无需使用存储库。如果您通过引用实体直接获取数据,那么您应该使用数据库字段名称发布的findBy或findOneBy。 请尝试以下方式:

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

class DefaultController extends Controller {

    public function indexAction() {

        $posts = this->forward('BlogBundle:Post:getLatestPosts', array(), array());

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