-3

我有一个关于 Symfony 应用程序的问题,我想输入我的控制器的“用户名”或“id”,并接收我的表“用户”和其他 2 个表中的信息,例如:一个用户有一个或更多级别,而且它有积分必须赚取积分才能解锁一个级别,我希望我的 dan 主页显示用户名和它的级别和程度,我是初学者,不了解我使用的书籍 symfony ,我使用 PARALLEL“symfony_book”和“symfony_cook_book”以及教程 youtube 我可以阻止,这是我的 cotroler 的代码“

/**  
* @Route("/{id}")      
* @Template()      
* @param $id=0      
* @return array      
*/     
public function getUserAction($id)     
{          
     $username = $this->getDoctrine()             
         ->getRepository('voltaireGeneralBundle:FosUser')              
         ->find($id);         
     if (!$username) {             
         throw $this->createNotFoundException('No user found for id '.$id);
     }         
     //return ['id' => $id,'username' => $username];         
     return array('username' => $username);              
}

我必须使用类之间的关系

use Doctrine\Common\Collections\ArrayCollection;
class Experience {      
    /**      
    * @ORM\OneToMany(targetEntity="FosUser", mappedBy="experience")      
    */     
    protected $fosUsers;

    public function __construct()     
    {
        $this->fosUsers = new ArrayCollection();
    }
}

class FosUser {      
    /**      
    * @ORM\ManyToOne(targetEntity="Experience", inversedBy="fosUsers")      
    * @ORM\JoinColumn(name="experience_id", referencedColumnName="id")      
    */     
    protected $fosUsers;   
}

我总是有一个错误

4

1 回答 1

0

在 Symfony 中,你不能在 Action 函数中返回一个数组!,Action 函数必须总是返回一个 Response 对象……所以如果你想在 Symfony 中向浏览器返回数据,Action 函数必须返回一个包裹在 Response 对象中的字符串。在您的控制器代码中,要将数组返回给浏览器,您可以将数组序列化为 JSON 并将其发送回浏览器:

public function getUserAction($id)     
{          
     $username = $this->getDoctrine()             
         ->getRepository('voltaireGeneralBundle:FosUser')              
         ->find($id);         
     if (!$username) {             
         throw $this->createNotFoundException('No user found for id '.$id);
     }                  
     return new Response(json_encode(array('username' => $username)));              
}

我建议您阅读有关 HTTP 协议、PHP 和 Symfony 的更多信息。

于 2015-08-17T21:14:37.407 回答