Reputation: 119
I want to create a route that will return a list of one of my entities, with only some of the fields of it.
I think it can be achieved with serialization groups but maybe it's not the easiest way to do it.
So I've thought to simply add a new custom route, called special_get
to test with the normalization_group
user:special
as follow :
/**
* @ApiResource(
* attributes={
* "normalization_context"={"groups"={"user:read", "user:list", "user:special"}},
* "denormalization_context"={"groups"={"user:write"}},
* "order"={"availabilities.start": "ASC"}
* },
* collectionOperations={
* "get"={
* "mehtod"="GET",
* "security"="is_granted('ROLE_USER')",
* "normalization_context"={"groups"={"user:list"}},
* },
* "special_get"={
* "method"="GET",
* "path"="/user/specialroute",
* "normalization_context"={"groups"={"user:special"}}
* },
* }
* )
* @ORM\Entity(repositoryClass=UserRepository::class)
*/
And apply this group
only to the few fields I want to return :
/**
* @ORM\Column(type="boolean")
* @Groups({"user:read", "user:list", "user:write", "user:special"})
*/
private $firstName;
/**
* @ORM\Column(type="string", length=255, nullable=true)
* @Groups({"user:write", "user:read", "user:list", "user:special"})
*/
private $photo;
/**
* @ORM\OneToMany(targetEntity=Availability::class, mappedBy="entityname", cascade={"remove"})
* @Groups({"user:read", "user:list", "user:write"})
* @ApiSubresource()
*/
private $availabilities;
That does create me a new route on the swagger interface as I want, but I get a 500
that says :
An error occured
Cannot select distinct identifiers from query with LIMIT and ORDER BY on a column from a fetch joined to-many association. Use output walkers.*
Does anyone have an idea on where this error might come from ?
Or if there is a better way to achieve recovering only a few fields form an entity on a special route ?
Thanks !
Upvotes: 1
Views: 926
Reputation: 237
You can use PropertyFilter so you can select specific fields
Enable the filter:
* @ApiFilter(PropertyFilter::class)
Import the class use ApiPlatform\Core\Serializer\Filter\PropertyFilter;
Now you can filter the serialization properties with the following query:
?properties[]=title&properties[]=shortDescription
You can add as many properties as you need.
Upvotes: 1
Reputation: 1443
So, regarding to the error message your problem is in order
attribute that orders results by availabilities.start
property that not added to your normalization group.
So you have to ways here:
availabilities
property to the normalization groupAs far as I know, api-platform didn't supports ordering attribute per operation at this moment, seems it shouldn't.
Upvotes: 1