I have two entities. Configuration and Role with a unidirection many-to-many relation in Configuration:
/**
* #var Role[]
*
* #ORM\ManyToMany(targetEntity="App\Entity\Role")
*/
private $roles;
Creation and update works as expected, but a
$this->entityManager->remove($configuration);
$this->entityManager->flush();
wont work (foreign key violation), because Doctrine will not delete the relation-dataset
It only works with a manual removal of the relation AND an additional flush before the removal of the entity.
foreach ($issueTypeConfiguration->getRoles() as $role) {
$issueTypeConfiguration->removeRole($role);
}
// It only works with this additional flush
$this->entityManager->flush();
$this->entityManager->remove($issueTypeConfiguration);
$this->entityManager->flush();
I expect Doctrine to delete the related datasets
Due to the manual creation of the many-to-many-table (Migration is not possible), I forgot to set the foreign key to DELETE CASCADE
I expected Doctrine to handle the deletion
Related
Within my database I have two related tables.
AppBooking
AppBookingService
AppBookingService has a foreign key to AppBooking
I use this method to make an insertion in both the first and second table.
public function bookingExecute($data){
try{
$this->em->beginTransaction();
$appBooking = $this->_fillAppBooking($data);
$this->em->persist($appBooking);
if(array_key_exists("appService",$data) && is_array($data['appService']) && count($data['appService']) > 0){
foreach($data['appService'] as $bookingService){
$appBookingService = $this->_fillAppBookingService($bookingService,$appBooking);
$this->em->persist($appBookingService);
$this->em->flush();
}
}
$this->em->flush();
$this->em->commit();
return $appBooking;
}catch (\Exception $ex){
$this->em->rollback();
throw new BookingException("",BookingError::BOOKING_QUERY_ERROR);
}
}
The data is written correctly
After that, in the same http request, I invoke the method below in order to have AppBooking Service data within my entity
$appBooking = $this->bookingService->findOne($id);
The problem that the AppBooking entity I get does not contain AppBookingService
The method
$appBooking->getServices()->count()
returns 0
If I make the same call in another http request I get the desired result.
It is as if doctrine did not update the entity in that same request
This is a part of AppBooking
/**
* #var Collection
* #ORM\OneToMany(targetEntity="AppBookingService", mappedBy="idBooking")
*/
private $services;
public function __construct() {
$this->services = new ArrayCollection();
}
This is part of AppBookingService
/**
* #var \Entity\Entity\AppBooking
*
* #ORM\ManyToOne(targetEntity="Entity\Entity\AppBooking", inversedBy="services")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="ID_BOOKING", referencedColumnName="ID_BOOKING", nullable=true)
* })
*/
private $idBooking;
This is because when running
$appBooking = $this->bookingService->findOne($id);
The entity is fetched from his internal proxy cache. No database query is executed to get the entity `s data. The same is true for its already loaded associations. The Proxy cache is valid during the execution of a http request.
To solve this, you either have to update the $services Collection manually or refresh the entity.
$this->em->refresh($appBooking);
Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been persisted.
You can also clear the entire entity manager cache before calling the findOne() method.
$this->em->clear();
Clears the EntityManager. All entities that are currently managed by this EntityManager become detached.
References
How do I force doctrine to reload the data from the database?
I have a complex/nested object created by automatic hydration from Zend\Form data. Now I want to save it with Doctrine 2. The best case would be just one persist(...) and one flush(...) call on the top level. But it doesn't work like this. So now I have following problem:
There are objects User and Order. The relationship is 1:n (so, 1 User has n Orders). The User exists already. When a User Joe tries to save more than one Order (e.g. its second order), an error occurs:
A new entity was found through the relationship '...\Order#user' that was not configured to cascade persist operations for entity: ...\User#000000003ba4559d000000005be8d831. 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"}). If you cannot find out which entity causes the problem implement '...\User#__toString()' to get a clue.
Allright, I add cascade={"persist"} (though it doesn't make sense here, but anyway, just to try it out):
class Order
{
...
/**
* #var User
*
* #ORM\ManyToOne(targetEntity="User", cascade={"persist"})
*/
protected $user;
...
}
Now it works, if the given User doesn't exist: An Order and a User is created.
But if the User exists, an error occurs:
An exception occurred while executing 'INSERT INTO user (username, role, created, updated) VALUES (?, ?, ?, ?)' with params ["myusername", "member", null, null]:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'myusername' for key 'username_UNIQUE'
How to handle the saving so, that the User only gets saved, if it doesn't exist yet?
The solution is to persist the User before saving the referencing entity. If it doesn't exist yet, it needs to be created (persisted and flushed) first:
$user = $this->entityManager->getRepository(User::class)->findOneBy(
['username' => $dataObject->getUser()->getUsername()]
);
if (! $user) {
$this->entityManager->persist($dataObject->getUser());
$this->entityManager->flush($dataObject->getUser());
$user = $this->entityManager->getRepository(User::class)->findOneBy(
['username' => $dataObject->getUser()->getUsername()]
);
}
$dataObject->setUser($user);
$this->entityManager->persist($dataObject);
$this->entityManager->flush();
And the cascade={"persist"} should not be used, since it actually doesn't make sense in this case.
EDIT
Or even easier:
$user = $this->entityManager->getRepository(User::class)->findOneBy(
['username' => $dataObject->getUser()->getUsername()]
);
if ($user) {
$dataObject->setUser($user);
} else {
$this->entityManager->persist($dataObject->getUser());
}
$this->entityManager->persist($dataObject);
$this->entityManager->flush();
For eg I have entities like User,Item, Image. User has many items. Item has many images.
Which delete option should I choose, cascade={'remove'} or onDelete=Cascade ?
Also I have life cycle callbacks on Image. I know the difference between above mentioned cascade options. I was wondering if I used onDelete=cascade option, on deleting a User object, will the life cycle callback like PostRemove() be called ?
Here are my entities:
//User.php
class User {
/**
* #ORM\OneToMany(targetEntity="Item", mappedBy="user", onDelete="CASCADE")
*/
private $items;
}
//Item.php
class Item {
/**
* #var User
*
* #ORM\ManyToOne(targetEntity="User", inversedBy="items")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* })
*/
private $user;
/**
* #ORM\OneToMany(targetEntity="ItemImage", mappedBy="item",onDelete="CASCADE")
*/
protected $images;
}
//ItemImage.php
class ItemImage {
/* Setters and getter **/
/**
* #var Items
*
* #ORM\ManyToOne(targetEntity="Item", inversedBy="images")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="item_id", referencedColumnName="id")
* })
*/
private $item;
/**
* #ORM\PostRemove()
*/
public function removeUpload() {
unlink($this->getUploadDir() . '/' . $this->imageName);
}
}
My question is when a user is deleted, will all the items associated with user and images related to the items be deleted ? I also want the PostRemove() callback of Image entity be called when User is deleted ? Which option should I use, onDelete="cascade" or cascade={'remove'} for such cases?
onDelete='CASCADE' will add an SQL level ON DELETE CASCADE. So yes, the images will be deleted from the table. This is very efficient because the database handles the deletes.
To have the listener called cascade={'remove'} is necessary. This makes Doctrine fetch the object's graph, which is slower.
Both options may be specified at the same time. In this case Doctrine will act as described in the last paragraph, but DELETEs not coming from Doctrine will cascade correctly, too; no listeners will be called in this case obviously.
I would tend to specify cascade={'remove'} only in this case to avoid accidental DELETEs without the listener being called (if there is no cleanup task for unreferenced files).
Details can be found in the Doctrine documentation.
Is there any way to get an entity ID before the persist/flush?
I mean:
$entity = new PointData();
$form = $this->createForm(new PointDataType(), $entity);
If I try $entity->getId() at this point, it returns nothing.
I can get it working by:
$em->persist($entity);
$em->flush();
(supposing $em = $this->getDoctrine()->getEntityManager();)
How can I achieve this?
If you want to know the ID of an entity before it's been persisted to the database, then you obviously can't use generated identifiers. You'll need to find some way to generate unique identifiers yourself (perhaps some kind of hash function can produce unique-enough values).
This is rarely a good idea, though, so you should be careful.
I would think very carefully about why I need to know the identifier before flush. Doctrine is quite good at letting you build up a big object graph, and persist/flush it all at once. It seems likely that you've got something ugly in your architecture that you're trying to work around. It might be a good idea to review that before going down the application-generated-id route.
You can use the #PostPersist annotation. A method annotated with that will be executed just before the flush terminate and the entity Id is available already.
https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/events.html
postPersist - The postPersist event occurs for an entity after the entity has been made persistent. It will be invoked after the database insert operations. Generated primary key values are available in the postPersist event.
<?php
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
*/
class PointData
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
...
/**
* #ORM\PostPersist
*/
public function onPostPersist()
{
// Put some simple logic here that required the auto-generated Id.
$this->doSomething($this->id);
}
...
}
you can use an auto generate ID to get a key like universally unique identifiers (UUID) or you can take the events of symfony:
postFlush - The postFlush event occurs at the end of a flush operation.
Doctrine best practices says,
You should avoid auto-generated identifiers. because:
Your DB operations will block each other
You are denying bulk inserts
You cannot make multi-request transactions
Your object is invalid until saved
Your object does not work without the DB
So you can use UUIDS instead
public function __construct() {
$this->id = Uuid::uuid4();
}
Also, Doctrine supports the UUID generation strategy since version 2.3.
Not sure why you need the ID before flushing, but, if you really need to persist the entity without saving to the database you can try using Transactions.
Try something like this:
$em->beginTransaction();
$em->persist($entity);
$em->flush();
$id = $entity->getId();
//do some stuff and save when ready
$em->commit();
$em = $this->getDoctrine()->getManager();
$entity = new PointData();
$em->persist($entity);
$entity->getId() <-- return <int>
$em->flush();
after persist you can get id
I'm having a hard time making sense of the Doctrine manual's explanation of cascade operations and need someone to help me understand the options in terms of a simple ManyToOne relationship.
In my application, I have a table/entity named Article that has a foreign key field referencing the 'id' field in a table/entity named Topic.
When I create a new Article, I select the Topic from a dropdown menu. This inserts an integer into the 'topic_id' foreign key field in the Article table.
I have the $topic association set up in the Article entity like this:
/**
* #ManyToOne(targetEntity="Topic")
* #JoinColumn(name="topic_id", referencedColumnName="id", nullable=false)
*/
private $topic;
The Topic entity doesn't have any reciprocating annotation regarding the Article entity. Topics don't care what Articles reference them and nothing needs to happen to a Topic when an Article that references the Topic is deleted.
Because I'm not specifying the cascade operation in the Article entity, Doctrine throws an error when I try to create a new Article: "A new entity was found through a relationship that was not configured to cascade persist operations. Explicitly persist the new entity or configure cascading persist operations on the relationship."
So I know I need to choose a cascade operation to include in the Article entity, but how do I know which operation to choose in this situation?
From reading the Doctrine manual, "detach" sounds like the right option. But researching others' similar questions here and here makes me think I want to use "persist" instead.
Can anyone help me understand what "persist," "remove," "merge," and "detach" mean in terms of a simple ManyToOne relationship like the one I've described?
In the Doctrine2 documentation "9.6. Transitive persistence / Cascade Operations" there are few examples of how you should configure your entities so that when you persist $article, the $topic would be also persisted. In your case I'd suggest this annotation for Topic entity:
/**
* #OneToMany(targetEntity="Article", mappedBy="topic", cascade={"persist", "remove"})
*/
private $articles;
The drawback of this solution is that you have to include $articles collection to Topic entity, but you can leave it private without getter/setter.
And as #kurt-krueckeberg mentioned, you must pass the real Topic entity when creating new Article, i.e.:
$topic = $em->getRepository('Entity\Topic')->find($id);
$article = new Article($topic);
$em->persist($article);
$em->flush();
// perhaps, in this case you don't even need to configure cascade operations
Good luck!
If you have a #OneToMany unidirectional association, like that described in section 6.10 of the Doctrine Reference, then most likely you forgot to persist the Topic before calling flush. Don't set the topic_id primary key in Article. Instead set the Topic instance.
For example, given Article and Topic entities like these:
<?php
namespace Entities;
/**
#Entity
#Table(name="articles")
*/
class Article {
/**
* #Id
* #Column(type="integer", name="article_id")
* #GeneratedValue
*/
protected $id;
/**
* #Column(type="text")
*/
protected $text;
/**
* #ManyToOne(targetEntity="Topic", inversedBy="articles")
* #JoinColumn(name="topic_id", referencedColumnName="topic_id")
*/
protected $topic;
public function __construct($text=null)
{
if (!is_null($text)) {
$this->text = $text;
}
}
public function setArticle($text)
{
$this->text = $text;
}
public function setTopic(Topic $t)
{
$this->topic = $t;
}
}
<?php
namespace Entities;
/**
#Entity
#Table(name="topics")
*/
class Topic {
/**
* #Id
* #Column(type="integer", name="topic_id")
* #GeneratedValue
*/
protected $id;
public function __construct() {}
public function getId() {return $this->id;}
}
After you generate the schema:
# doctrine orm:schema-tool:create
your code to persist these entities would look like something this
//configuration omitted..
$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);
$topic = new Entities\Topic();
$article1 = new Entities\Article("article 1");
$article2 = new Entities\Article("article 2");
$article1->setTopic($topic);
$article2->setTopic($topic);
$em->persist($article1);
$em->persist($article2);
$em->persist($topic);
try {
$em->flush();
} catch(Exception $e) {
$msg= $e->getMessage();
echo $msg . "<br />\n";
}
return;
I hope this helps.