symfony 2中的自定义存储库类不起作用

时间:2014-10-09 08:46:12

标签: php symfony doctrine

我是symfony 2的新手并且真的很喜欢它。有时我不知道它是在文档中还是在我自己中。

几个小时以来,我试图让存储库类工作并通过问题以及那些对我没有帮助的学说文档。

所以这些链接都没有帮助我

实际上我不应该做很多事情来完成正确的结果,但我总是会收到一个错误:"未定义的方法' findAllOrderedByName'。方法名称必须以findBy或findOneBy开头! 500内部服务器错误 - BadMethodCallException"

我认为我的命名空间和/或使用语句有问题,但我不知道。任何人都可以告诉我我做错了什么,也许还应该做些什么才能做到正确?我想要的只是让方法findAllOrderedByName()起作用。

所以这就是我所拥有的:

的Symfony / SRC / Acme公司/ StoreBundle /实体/ Product.php

<?php

namespace Acme\StoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="Acme\StoreBundle\Entity\ProductRepository")
 */
class Product
{ 
    // all the code which was/is working
}

的Symfony / SRC / Acme公司/ StoreBundle /实体/ ProductRepository.php

<?php

namespace Acme\StoreBundle\Entity;
use Doctrine\ORM\EntityRepository;

class ProductRepository extends EntityRepository
{
    public function findAllOrderedByName()
    {
        return $this->getManager()
            ->createQuery(
                'SELECT p FROM AcmeStoreBundle:Product p ORDER BY p.name ASC'
            )
            ->getResult();
    }
}

的Symfony / SRC / Acme公司/ StoreBundle /控制器/ DefaultController.php

<?php

namespace Acme\StoreBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Acme\StoreBundle\Entity\Product;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    public function showAction()
    {
        $em = $this->get('doctrine')->getManager();
        $products = $em->getRepository('AcmeStoreBundle:Product')
            ->findAllOrderedByName();
        return $this->render('AcmeStoreBundle:Default:showAll.html.twig', array('products' => $products));
    }
}

感谢阅读和帮助!

2 个答案:

答案 0 :(得分:3)

感谢所有帮助过的人。我想通了, IT是我自己当然symfony没有任何问题,但我做的更多:

命令后:

 php app/console generate:bundle --namespace=Acme/StoreBundle

我选择

"Determine the format to use for the generated configuration." --> xml

而不是注释。所以我不得不改变我的

~/Projects/Symfony/src/Acme/StoreBundle/Resources/config/doctrine/Product.orm.xml

文件。 <entity name="Acme\StoreBundle\Entity\Product">

<entity
        name="Acme\StoreBundle\Entity\Product"
        repository-class="Acme\StoreBundle\Entity\ProductRepository">

答案 1 :(得分:0)

试试这个:

$products = $this->getDoctrine()
        ->getRepository('AcmeStoreBundle:Product')
        ->findAllOrderedByName();

public function findAllOrderedByName(){
    return $this->getEntityManager()
        ->createQuery(
        'SELECT p FROM AcmeStoreBundle:Product p ORDER BY p.name ASC'
        )
        ->getResult();
}

您还可以尝试不同的功能名称。而不是findAllOrderedByName()选择例如findProducts()。

相关问题