未定义的偏移量:0。学说和本土 sql

Undefined offset: 0. Doctrine and native sql

我有一点问题,我想打印用户的 id,但是我有一个错误:"Undefined offest: 0"。这是我的代码:

$rsm = new ResultSetMapping();
$em = $this->getDoctrine()->getManager(); 
$user= $this->get('security.context')->getToken()->getUser();
$query = $em->createNativeQuery('SELECT id FROM fos_user WHERE username_canonical = ?', $rsm);
$query->setParameter(1, $user);
$users = $query->getResult();
echo $users[0]['id'];

有人知道哪里出了问题吗?

更改字符串:

$query->setParameter(1, $user);

$query->setParameter(1, $user->getUsernameCanonical());
  1. EntityResultFieldResult添加到$rsm

    $rsm = new ResultSetMapping();
    $rsm->addEntityResult('App\UserBundle\Entity\User', 'u');
    $rsm->addFieldResult('u', 'id', 'id');
    
  2. 改变setParameter

    $user$user->getUsernameCanonical();

  3. 获取结果

    foreach($users as $user)
    {
        echo $user->getId();
    }