Symfony - 调用数组上的成员函数

时间:2017-10-30 11:33:37

标签: php symfony

我有以下功能:

public function getUserMediaAction(Request $request)
{
    $data = $this->decodeToken($request);
    $username = $data['email'];
    $user = $this->getDoctrine()->getRepository('ApplicationSonataUserBundle:User')
                 ->findOneBy(['email' => $username]);
    $idUser = $user->getId();
    $media = $this->getDoctrine()->getRepository('ApplicationSonataUserBundle:User')
                  ->findNewbieAllData($idUser);

    return new JsonResponse(['media' => $media->getPath()]);
}

findNewbieAllData:

public function findNewbieAllData($id_newbie)
{
    $sql = "SELECT m
            FROM ApplicationSonataUserBundle:User u
            JOIN ApplicationSonataUserBundle:Media m
            WHERE u.id=?1";

    $query = $this->getEntityManager()

                    ->createQuery($sql)
                    ->setParameter(1, $id_newbie);

    $result = $query->getArrayResult();
    return $result;
}

遗憾地返回以下错误:

Call to a member function getPath() on array

Stack Trace

in src\CoolbirdBundle\Controller\UserController.php at line 97   -
        $media = $this->getDoctrine()->getRepository('ApplicationSonataUserBundle:User')
                      ->findNewbieAllData($idUser);
        return new JsonResponse(['media' => $media->getPath()]);
    }

有人会知道如何解决这个问题吗?

提前谢谢

2 个答案:

答案 0 :(得分:2)

请尝试以下方法:

return new JsonResponse(['media' => $media[0]->getPath()]);

修改:查看var_dump输出,您应该尝试这样做:

return new JsonResponse(['media' => $media[0]['path']]);

答案 1 :(得分:1)

方法findNewbieAllData使用数组来水合数据。

$result = $query->getArrayResult();
    return $result;

在这里查看getArrayResult方法:

https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php

改为使用getResult方法。