学说实体的国家

Suddenly doctrine orm has such a behavior:

$em = $connection->getEntityManager(); $entity = $em->find('SomeModel', 1); $entity->setName('name'); $em->flush();

And it will affect a database because a model have managed state.

$em->getUnitOfWork()->getEntityState($entity); //1 === UnitOfWork::STATE_MANAGED

It spoild a lot of nerves for me and now i want to know when can i get entities from a database with managed state?

As far as I know, any entity you get from the entity manager will initially be in a managed state. The only time you will need to explicitly manage an entity with persist() is if it is created outside the entity manager, like:

$entity = new SomeModel;
$em->persist($entity);

or created in a different entity manager (in which case it would still be managed, but by the other entity manager, so calling flush on your entity manager would not affect your database).

If you don't want an entity to be managed, you can detach it.

$em->detach($entity);

From the documentation:

An entity is detached from an EntityManager and thus no longer managed by invoking the EntityManager#detach($entity) method on it or by cascading the detach operation to it. Changes made to the detached entity, if any (including removal of the entity), will not be synchronized to the database after the entity has been detached.