简体   繁体   English

Symfony2的自定义存储库问题-注意:未定义偏移量:0

[英]Custom repository problems with Symfony2 - Notice: Undefined offset: 0

I'm trying to move my query into a custom repository class. 我正在尝试将查询移到自定义存储库类中。 Here is what I've got so far 这是我到目前为止所得到的

class MovieRepository extends EntityRepository
{
    public function showMovie($movie)
    {
    $em = $this->getEntityManager();

    $qb = $em->createQueryBuilder('m');

    $query = $qb->select('m.title', 'm.img', 'u.username')
        ->where('m.title = :movie')
        ->leftJoin('m.user', 'u')
        ->setParameter('movie', $movie)
        ->getQuery();

    return $query->getSingleResult();
    }
}

I use it like this in my controller: 我在控制器中像这样使用它:

$em = $this->getDoctrine()->getManager();
$result = $em->getRepository('AMovieBundle:Movie')->showMovie($movie);

I did put the @ORM\\Entity(repositoryClass="A\\MovieBundle\\Entity\\MovieRepository") in my entity and the namespaces and folders are correct, and my relations from the movie to the user is correct as this worked before, when I had the query in the controller. 我确实将@ORM \\ Entity(repositoryClass =“ A \\ MovieBundle \\ Entity \\ MovieRepository”)放在我的实体中,并且名称空间和文件夹是正确的,并且当我之前从电影到用户的关系是正确的时,在控制器中有查询。

The primary error I keep getting is this: 我一直得到的主要错误是:

Notice: Undefined offset: 0 in /Applications/MAMP/htdocs/symfony2test/vendor/doctrine/orm/lib/Doctrine/ORM/QueryBuilder.php line 271 注意:/Applications/MAMP/htdocs/symfony2test/vendor/doctrine/orm/lib/Doctrine/ORM/QueryBuilder.php第271行中的未定义偏移量为0

Line 271 in the query builder is this: 查询构建器中的271行是这样的:

public function getRootAlias()
{
    $aliases = $this->getRootAliases();
    return $aliases[0];
}

I have no idea where to go from here and any help would be greatly appreciated. 我不知道从这里去哪里,任何帮助将不胜感激。

A quick tip, the function getRootAlias() returns the alias created for the query, which is in your case "m". 快速提示,函数getRootAlias()返回为查询创建的别名,在您的情况下为“ m”。

If i make an educated guess i'll try this (note the select syntax) : 如果我做出有根据的猜测,我会尝试一下(请注意选择语法):

$query = $qb->select('m.title, m.img, u.username')
            ->where('m.title = :movie')
            ->leftJoin('m.user', 'u')
            ->setParameter('movie', $movie)
            ->getQuery();

You are already inside an EntityRepository, you don't need to call $this->getEntityManager() . 您已经在EntityRepository内部,不需要调用$this->getEntityManager()

Just do : $qb = $this->createQueryBuilder('m'); 只要做: $qb = $this->createQueryBuilder('m');

That should fix your problem. 那应该解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM