Skip to content

Instantly share code, notes, and snippets.

@botris
Last active June 4, 2021 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save botris/eea995da0043c7599b9e873561d5b909 to your computer and use it in GitHub Desktop.
Save botris/eea995da0043c7599b9e873561d5b909 to your computer and use it in GitHub Desktop.
Update many entities with API Platform
<?php
class BulkUpdateController
{
private EntityWithManyProperties $entityWithManyProperties;
public function __construct(EntityWithManyProperties $entityWithManyProperties)
{
$this->entityWithManyProperties = $entityWithManyProperties;
}
public function __invoke(EntityWithManyPropertiesInput $data): Response
{
$ids = [];
foreach ($data->entities as $entity) {
$ids[] = $entity->getId();
}
$result = $this->entityWithManyProperties->updateBulk($ids, $data->someProperty);
return new Response(sprintf('Updated %s entities', $result), 200);
}
}
<?php
use App\Controller\BulkUpdate;
use App\Entity\Dto\EntityWithManyPropertiesInput;
/**
* @ApiResource(
* collectionOperations={
* "get",
* "post",
* "bulk-update": {
* "method": "POST",
* "path": "/myentity/bulk-update.{_format}",
* "input": EntityWithManyPropertiesInput::class,
* "controller": BulkUpdateController::class,
* "read": false,
* }
* }
*/
class EntityWithManyProperties
<?php
class EntityWithManyPropertiesInput
{
/**
* @var EntityWithManyProperties[]
*/
public array $entities;
public bool $someProperty;
}
<?php
/**
* Need DataTransformer as per: https://github.com/api-platform/core/issues/3295#issuecomment-569092512
*/
class EntityWithManyPropertiesInputTransformer implements DataTransformerInterface
{
/**
* @param EntityWithManyPropertiesInput $object
*/
public function transform($object, string $to, array $context = []): EntityWithManyPropertiesInput
{
return $object;
}
public function supportsTransformation($data, string $to, array $context = []): bool
{
if ($data instanceof EntityWithManyProperties) {
// Already transformed.
return false;
}
return EntityWithManyProperties::class === $to && ($context['input']['class'] ?? null) === EntityWithManyPropertiesInput::class;
}
}
<?php
class EntityWithManyPropertiesRepository extends ServiceEntityRepository
{
//...
public function updateBulk(array $entityIds, bool $someProperty)
{
$qb = $this->createQueryBuilder('n');
$qb->update()
->set('n.someProperty', ':property')
->where('n.id IN (:ids)')
->setParameter('property', $someProperty)
->setParameter('ids', $entityIds);
return $qb->getQuery()
->getResult();
}
}
{
"entities": [
"/api/entity/1",
"/api/entity/3"
],
"someProperty": true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment