Symfony2 Doctrine Custom Repository Class [Semanti

2019-02-20 14:14发布

I'm really new in Symfony 2 and Doctrine, and have a simple problem:

There is a pretty simple code in my repository:

<?php

namespace BakeryIT\BakeryBundle\Entity;

use Doctrine\ORM\EntityRepository;

class ProjectRepository extends EntityRepository
{
    public function findHistory(){
        return $this->getEntityManager()
        ->createQueryBuilder()
        ->select('p')
        ->from('Project','p')
        ->getQuery()
        ->getResult();
    }
}

And two simple functions in my controller:

<?php

namespace BakeryIT\BakeryBundle\Controller;

/*
...
*/

class ProjectController extends Controller
{
    public function indexAction()
    {
        return $this->index('Project', 'findHistory');
    }
}

And Controller looks like this:

public function index($entity, $query = 'findAll')
{
    $repository = $this->getDoctrine()
        ->getRepository('BakeryBundle:'.$entity);

    $data = $repository->$query();

    return $this->render('BakeryBundle:'.$entity.':index.html.twig',
    array('data' => $data));
}

This code throw me the Semantical Error [Semantical Error] line 0, col 14 near 'Project p': Error: Class 'Project' is not defined.

On the other hand everything works perfectly if I change this line in my repository:

->from('Project','p')

to

->from('BakeryIT\BakeryBundle\Entity\Project','p')

I don't know why this example doesn't work in the first case. Namespace in my BakeryIT\BakeryBundle\Entity\Project is set in this way:

namespace BakeryIT\BakeryBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Project
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="BakeryIT\BakeryBundle\Entity\ProjectRepository")
 */
class Project
{
/*
..
*/
}

2条回答
你好瞎i
2楼-- · 2019-02-20 14:37

On my local system I could use

$entityManager->createQuery('DELETE FROM BellaShopBundle:cache c WHERE c.expires < :now')->setParameter('now', $date);

But on production it was necessary to capitalise the entity or class name, which I guess I was thinking of as the table name, thus:

$entityManager->createQuery('DELETE FROM BellaShopBundle:Cache c WHERE c.expires < :now')->setParameter('now', $date);
查看更多
男人必须洒脱
3楼-- · 2019-02-20 14:45

In order to use the short form, you'll need to provide the bundle name too. This is constructed from the vendor and bundle name. In your case it would be something like:

from('BakeryITBakeryBundle:Project')

See the following link for more information on bundles:

http://symfony.com/doc/current/cookbook/bundles/best_practices.html

查看更多
登录 后发表回答