学说:我可以只冲洗一类实体吗?

时间:2016-11-18 16:40:27

标签: php symfony doctrine-orm

我喜欢将Doctrine存储库作为服务传递到Symfony2并避免传递EntityManager的一般想法。然而,虽然在读取数据时它很好,但保存逻辑在这里有点问题。

我们将此作为参考:http://php-and-symfony.matthiasnoback.nl/2014/05/inject-a-repository-instead-of-an-entity-manager/,但将持久性和刷新分开:

class DoctrineORMCustomerRepository extends EntityRepository implements CustomerRepository
{
    public function persist(Customer $customer)
    {
        $this->_em->persist($customer);
    }

    public function flush()
    {
        $this->_em->flush();
    }
}

问题是您在特定存储库中刷新所有实体中的所有更改。

现在,是否可以只刷新一类实体? (可能级联到依赖实体),所以我基本上可以做类似的事情:

foreach ($customers as $customer) {
    $this->customerRepository->persist($customer);
}

$this->customerRepository->flush();

我考虑过这样的事情:

$this->_em->flush(getUnitOfWork()->getIdentityMap()[$this->_entityName]);

但我一定是误解了一些东西,因为它没有用。

编辑:是的,我知道我可以做$this->_em->flush($entity),但逐一进行此操作并不是最理想的。我甚至知道我可以做$this->_em->flush($arrayOfEntities),但要做出#34; foreach"示例以这种方式工作我必须跟踪存储库中所有持久化的实体,并复制一些Doctrine内部。

3 个答案:

答案 0 :(得分:11)

试试这个:

$em->flush($entity);

然后,doctrine只会刷新$ entity,忽略任何其他实体。

答案 1 :(得分:3)

您可以尝试将要保留的实体实例传递给实体存储库的flush方法,例如:

    $this->_em->flush($entity);

根据Doctrine/ORM/EntityManager类的文档,方法flush

 * If an entity is explicitly passed to this method only this entity and
 * the cascade-persist semantics + scheduled inserts/removals are synchronized.
 *
 * @param null|object|array $entity
 *
 * @return void
 *
 * @throws \Doctrine\ORM\OptimisticLockException If a version check on an entity that
 *         makes use of optimistic locking fails.
 * @throws ORMException
 */
public function flush($entity = null)

希望这个帮助

答案 2 :(得分:1)

简答:是的。

答案很长:你必须循环遍历所有已加载的实体,检查它的类,如果有你需要的类,则刷新实体。

请参阅\ ORM \ EntityManager flush() function

$this->unitOfWork->commit($entity);

\ORM\UnitOfWork类有一些您可以使用的功能,从commit() function

开始