我试图覆盖 PUT 操作以在特定条件下执行我的操作。也就是说,如果发送的对象与原始对象(来自数据库)不同,那么我需要创建一个新对象并在不改变原始对象的情况下返回它。
现在当我执行查询时,我得到了一个新对象,正如预期的那样,但问题是原始对象也发生了变化
实体
#[ApiResource(
operations: [
new Get(),
new GetCollection(),
new Post(controller: CreateAction::class),
new Put(processor: EntityStateProcessor::class),
],
paginationEnabled: false
)]
class Entity
实体状态处理器
final class PageStateProcessor implements ProcessorInterface
{
private ProcessorInterface $decorated;
private EntityCompare $entityCompare;
public function __construct(ProcessorInterface $decorated, EntityCompare $entityCompare)
{
$this->decorated = $decorated;
$this->entityCompare = $entityCompare;
}
public function process($data, Operation $operation, array $uriVariables = [], array $context = [])
{
if (($this->entityCompare)($data)) { // checking for object changes
$new_entity = clone $data; // (without id)
// do something with new entity
return $this->decorated->process($new_entity, $operation, $uriVariables, $context);
}
return $data;
}
}
我不明白为什么会这样,所以我将原始对象的克隆返回给进程。如果有人能告诉我我的错误是什么,那就太好了。
我在返回过程之前也尝试了以下
$this->entityManager->refresh($data);
- 这里我假设对象的原始实例将使用数据库中的数据进行更新,而对象不会使用查询中的数据进行更新$this->entityManager->getUnitOfWork()->detach($data);
- 在这里我假设对象将不再可管理并且不会被更新但在这两种情况下,原始 $data 的状态都会发生变化。
我正在使用 ApiPlatform 3.0.2
错误是主要实体与附加实体相关,因此仅将主要实体与
UnitOfWork
分离是不够的。所以使用Doctrine\ORM\UnitOfWork->clear(YourEntity::class)
方法分离实体的所有实例,你对关系做同样的事情。
一旦实体被分离,克隆实体就变得毫无意义,因为以前的实体实例不是由 Doctrine ORM 管理的,所以我的代码重新排列如下:
public function process($data, Operation $operation, array $uriVariables = [], array $context = [])
{
if (($this->entityCompare)($data)) { // checking for object changes
$this->getEntityManager()->getUnitOfWork()->clear(Entity::class);
$this->getEntityManager()->getUnitOfWork()->clear(EelatedEntity::class);
// do something with new entity
return $this->decorated->process($data, $operation, $uriVariables, $context);
}
return $data;
}
面临同样的问题......有什么消息吗?
我通过数据库的存储库获取实体并在更新后刷新。
这似乎不对