我使用FOSRestController用于api和ExclusionPolicy,并且Expose用于实体,我对某些逻辑有两个操作但是当我返回实体$ bits时,我想要可见的不同字段,例如一个动作只是id和创建,第二个动作只提交了projectId。因为现在我返回有注释@Expose的文件,但这适用于所有操作。我有问题如何为类配置实体字段BitController扩展FOSRestController进行另一个操作?我使用@Groups({" list"})和控制器
$bits = $this->get('serializer')->serialize(new Bit(), 'json', SerializationContext::create()->setGroups(array('list')));
但是$ bits = {}可能这是因为$ bits数组?
/**
* Bit
*
* @ORM\Table(name="bit")
* @ORM\Entity(repositoryClass="Artel\ProfileBundle\Entity\Repository\BitRepository")
* @ExclusionPolicy("all")
*/
class Bit
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @Expose()
* @Groups({"list"})
*/
private $id;
/**
* @var datetime $created
*
* @Gedmo\Timestampable(on="create")
* @ORM\Column(type="datetime")
* @Expose()
*/
private $created;
/**
* @ORM\ManyToOne(targetEntity="Project", inversedBy="bit")
* @ORM\JoinColumn(name="project_id", referencedColumnName="id", onDelete="CASCADE")
*
* @Groups({"list"})
*/
private $projectId;
class BitController extends FOSRestController
{
public function getBitByProjectAction($id, $token)
{
$security = $this->get('security.context');
$user = $this->getDoctrine()->getRepository('ArtelProfileBundle:Users')->findOneBySecuritytoken($token);
if (!empty($user) || $security->isGranted('ROLE_ADMIN') ) {
$bits = $this->getDoctrine()->getManager()
->getRepository('ArtelProfileBundle:Bit')
->findBitByProject($id, $token);
if (!$bits) {
throw new NotFoundHttpException();
}
$view = $this->view($bits, 200)
->setSerializationContext(SerializationContext::create()->setGroups(array('list')))
;
return $this->handleView($view);
public function getBitsProjectsAction($token)
{
$user = $this->getDoctrine()->getRepository('ArtelProfileBundle:Users')->findOneBySecuritytoken($token);
$view = View::create();
if (!empty($user) && !empty($token)) {
$bits = $this->getDoctrine()->getRepository('ArtelProfileBundle:Bit')->findClientsBitsByProjects($token);
$view->setStatusCode(200);
$view = $this->view($bits, 200)
->setSerializationContext(SerializationContext::create()->setGroups(array('list')))
;
return $this->handleView($view);
}else{
$view->setStatusCode(101);
}
return $view;
}
解决
$view = $this->view($bits, 200)
->setSerializationContext(SerializationContext::create()->setGroups(array('list')))
;
return $this->handleView($view);