F
F
feedbee2012-05-25 10:44:01
PHP
feedbee, 2012-05-25 10:44:01

Entity Relationships in ORM Doctrine2

For a long time I wrote a database access layer at the level of SQL queries. Now I decided to try to switch to ORM. In particular, Doctrine2. There is one conceptual misunderstanding of the part of the process of working with entities.

Example: The problem is the following. At one point in the code, I requested $user, changed it, and tried to save. If the save went well, then there would be no problem. But it failed for me. The $user object has been changed in the code, but not in the database. Below in the code, the $user request is independent of the first part. EntityManager will return the same

try {
$user = $entityManager->find('User', 1);
$user->setName('New name');
$entityManager->flush();
} catch (...)
{
// изменение провалилось по какой-то причине, т.е. объект не был сохранен
}

// ...

$user = $entityManager->find('User', 1);
$user->setOther('Other');
$entityManager->flush(); // <- здесь сохранится и [other], и [name], потому что [name] осталось измененным кодом выше



the object it returned the first time it was called, i.e. object with changed property [name]. But the bottom block of code doesn't know about it. By changing another field, the code makes a second save request. But this request from the point of view of the caller will be incorrect, because as a result, an UPDATE will be sent to two properties [name] and [other] at once, instead of only one [other].

I'm guessing I'm just not working with the ORM correctly. Help me, please, to understand the correct ideology and resolve the situation. The question is not what crutches to insert in the code so that it works as it should - I myself see a lot of options. The question is how to do it right.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
denver, 2012-05-25
@denver

I think in catch you need to do $entityManager-> detach ($user)

V
Vampiro, 2012-05-25
@Vampiro

Unlike the " SQL query layer " that you are accustomed to, the Doctrine does not seek to save every change in the database at the first sneeze of the user. Change the entities within reason, then update it all in the store once with a single flush(). This is correct and normal when your script does selects at the beginning of work, and updates/deletes at the end. And it’s wrong when a bunch of requests to modify different fields in the same table flies to the database during the script’s work. At first, it breaks a little, but you will dissonance and let it go =)

K
Kir ---, 2012-05-25
@SowingSadness

objects are persisted at $entityManager->flush()
docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-objects.html#persisting-entities

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question