【发布时间】:2016-12-14 01:37:42
【问题描述】:
我的composer.json(部分):
{
"require": {
"symfony/symfony": "3.1.*",
"jms/serializer-bundle": "^1.1",
"friendsofsymfony/rest-bundle": "^2.1"
}
}
我有一些实体,我想为列表操作返回部分数据并为查找操作完成。为此,我有这些文件:
产品.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;
/**
* @ORM\Entity
* @ORM\Table(name="represented")
* @JMS\ExclusionPolicy("ALL")
*/
class Product
{
/**
* @var integer
* @ORM\Column(type="integer", nullable=false, options={"unsigned"=true})
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var string
* @ORM\Column(type="string", nullable=false, length=48)
*/
protected $name;
/**
* @var Group
* @ORM\ManyToOne(targetEntity="Group", inversedBy="products")
* @ORM\JoinColumn(name="group_id", referencedColumnName="id")
*/
protected $group;
public function getId()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setGroup(Group $group)
{
$this->group = $group;
}
public function getGroup()
{
return $this->group;
}
}
ProductController.php
<?php
namespace AppBundle\Controller;
use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\FOSRestController;
use AppBundle\Entity\Product;
class ProductController extends FOSRestController
{
/**
* @Get("/product", name="list_products")
*/
public function listAction()
{
$products = $this->getDoctrine()
->getRepository('AppBundle:Product')
->findBy([], [ 'name' => 'ASC' ]);
$view = $this->view($products);
return $this->handleView($view);
}
/**
* @Get("/product/{id}", requirements={"id" = "\d+"}, name="get_product")
*/
public function getAction($id)
{
$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('AppBundle:Product')
->find($id);
if ( ! $product) {
$error = [
'error' => 'Product not found'
];
$view = $this->view($error, 404);
} else {
$view = $this->view($product);
}
return $this->handleView($view);
}
}
我希望能够不在列表结果中显示group 属性。为此,我尝试了一些方法,主要是与组。
- 只需为我要显示的属性配置组名
在我的名单上
Groups({"List"})并在 控制器@View(serializerGroups={"List"})。但这并没有 影响,因为所有属性都是可见的。 - 没有为整个实体配置
@ExclusionPolicy("all")也可以工作。 - 除了 ExclusionPolicy,
@Expose到我想要的所有属性 显示在部分或所有组中,但这使得所有属性都被标记 显示出来。
我还尝试了这些的更多变体,但没有改变结果。
【问题讨论】:
标签: php symfony fosrestbundle jmsserializerbundle