Skip to content

alwaysIdentifier annotation option implementation #373

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions core/serialization.md
Original file line number Diff line number Diff line change
Expand Up @@ -620,3 +620,49 @@ class Book
// ...
}
```

## Force Relations to be Serialized as IRIs

Sometimes, for instance when dealing with trees of resources, using only serialization groups can lead to huge payloads.
To limit these references you can use the `alwaysIdentifer` option, as its name suggest, it forces to serialize the relation as an IRI instead of embedding its data:

```php
// src/Entity/Category.php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiProperty;
use Doctrine\ORM\Mapping as ORM;

/**
* @ApiResource
* @ORM\Entity
*/
class Category
{
//...

/**
* @var ArrayCollection children categories
*
* @ORM\ManyToMany(targetEntity="Category")
* @ApiProperty(alwaysIdentifier=true)
*/
private $children;
}
```

A resource of this class will be serialized as:

```json
{
"@context": "/contexts/Category",
"@id": "/categories/1",
"@type": "Category",
"children": [
"/always_identifier_dummies/1"
]
}
```

Note that in trees an object will be always serialized only 1 time. The second time, the IRI will always be used because of the built-in circular reference handler.