I have two entities , user and store, they have a many-to-one relationship, before I create a user, I have to make sure a store is existed, it is not allowed to create a store while creating a user ,that means cascade={"persist"} can't be used.
Store class
public function addUser(User $user)
{
if (!$this->users->contains($user))
{
$this->users->add($user);
$user->setStore($this);
}
return $this;
}
before I create a user , I am pretty sure that a store is already existed.these code below is the way I used to create user
$store= $this->get('vmsp.store_provider')->getCurrentStore();
$store->addUser($user);
$userManager->updateUser($user);
code in updateUser method is not special:
$this->entityManager->persist($user);
$this->entityManager->flush();
code in getCurrentStore method:
public function getCurrentStore($throwException=true)
{
if (isset(self::$store)) {
return self::$store;
}
$request = $this->requestStack->getCurrentRequest();
$storeId = $request->attributes->get('storeId', '');
$store = $this->entityRepository->find($storeId);
if ($store === NULL&&$throwException) {
throw new NotFoundHttpException('Store is not found');
}
self::$store = $store;
return $store;
}
this gives me a error:
A new entity was found through the relationship 'VMSP\UserBundle\Entity\User#store' that was not configured to cascade persist operations for entity: ~ #1. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"})
thing is getting very interesting, why does a existed store become new entity? why does doctrine think that existed store entity as a new entity?
$this->get('vmsp.store_provider')->getCurrentStore();
does not really return a Doctrine object, so Doctrine doesn't really know it is persisted. Please show us this code .. – tchapupdateUser()
. As a side note you should avoid bidirectional relationships (see docs Best Practices-chapter) – dbrumannself::$store
and use proper caching instead. Your way will likely bring no (or close to no) performance gains, but introduces major headaches. This pretty much introduces global state that's difficult to test and might cause nasty side effects, e.g. when a different part of your code causes the current store to point to a different id. – dbrumann