Kal*_*mar 6 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();
}
}
Run Code Online (Sandbox Code Playgroud)
问题是您在特定存储库中刷新所有实体中的所有更改.
现在,是否可以只刷新一类实体?(可能级联到依赖实体),所以我基本上可以这样做:
foreach ($customers as $customer) {
$this->customerRepository->persist($customer);
}
$this->customerRepository->flush();
Run Code Online (Sandbox Code Playgroud)
我考虑过这样的事情:
$this->_em->flush(getUnitOfWork()->getIdentityMap()[$this->_entityName]);
Run Code Online (Sandbox Code Playgroud)
但我必须误解一些东西,因为它不起作用.
编辑:是的,我知道我可以做到$this->_em->flush($entity),但逐一做这件事并不是最理想的.我甚至知道我可以这样做$this->_em->flush($arrayOfEntities),但是为了使"foreach"示例以这种方式工作,我必须跟踪存储库中所有持久化的实体,复制一些Doctrine内部.
小智 11
试试这个:
$em->flush($entity);
Run Code Online (Sandbox Code Playgroud)
然后,doctrine只会刷新$ entity,忽略任何其他实体.
您可以尝试将要持久化的实体实例传递给实体存储库的flush方法,例如:
$this->_em->flush($entity);
Run Code Online (Sandbox Code Playgroud)
根据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)
Run Code Online (Sandbox Code Playgroud)
希望这有帮助