自定义存储库(REQUEST DQL)

时间:2015-10-23 14:23:53

标签: symfony doctrine-orm

当我想使用DQL请求添加自定义方法时出错。 错误:

  

未定义的方法'getAll'。方法名称必须以其中一个开头   findBy或findOneBy!

我的控制器:( SheetController.php)

<?php
namespace Test\FrontBundle\Controller;

use Doctrine\ORM\EntityNotFoundException;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Test\FrontBundle\Entity\Sheet;

class SheetController extends Controller
{
    public function sheetListAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $repository = $em->getRepository('TestFrontBundle:Sheet');

        $sheets = $repository->getAll();
        var_dump($sheets);
        return $this->render('TestFrontBundle:Sheet:sheetList.html.twig');
    }
    public function sheetAction($id, Request $request)
    {
        $repository = $this->getDoctrine()->getManager()->getRepository('TestFrontBundle:Sheet');
        $sheet = $repository->find($id);
        if(!$sheet)
        {
            throw new EntityNotFoundException();
        }
        return $this->render('TestFrontBundle:Sheet:sheet.html.twig', array('sheet' => $sheet));
    }
}
?>

我的存储库:(SheetRepository.php)

<?php

namespace Test\FrontBundle\Entity;

/**
 * SheetRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */

class SheetRepository extends \Doctrine\ORM\EntityRepository
{
    public function getAll()
    {
        $qb = $this->createQueryBuilder('s');

        $query = $qb;

        $result = $query->getQuery()->execute();

        return $result;
    }
}

拜托,你能帮帮我吗? :)

1 个答案:

答案 0 :(得分:0)

为什么不为此使用本机Doctrine查询findAll()?

public function sheetListAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $repository = $em->getRepository('TestFrontBundle:Sheet');

    $sheets = $repository->findAll();
    /***/
}

编辑 - 使用类存储库:

class SheetRepository extends \Doctrine\ORM\EntityRepository
{
    public function getAll()
    {
        return $this->createQueryBuilder('s')
           ->select('s')
           ->getQuery()
           ->getResult()
       ;
    }
}

在您的控制器中:将findAll()替换为getAll()