Save user id automatically to entities with Doctrine

Asked

Viewed 73 times

0

I use Doctrine 2 to map my system’s database. Most entities have a foreign key pointing to an entity "account".

When a user logs into the system, I add their account id to a session variable. Then I add an Sqlfilter to the Doctrine settings (bootstrap) this way:

$config->addFilter("conta", "\Classes\FiltroConta");

This statement adds a condition to any queries the system makes, something like

SELECT nome FROM pessoas WHERE nome = 'pedro' AND conta = 1

The condition conta = 1 is automatically added whenever the filter is configured. And number 1 is the id that is in the session variable.

Imagine that to persist a data in the entity people I need to do the following instruction:

//Obtem referencia da entidade conta
$conta = $em->getReference('Conta', $SESSION['idConta']);
$pessoa = new pessoas();
$pessoa->setNome('Pedro');
$pessoa->conta($conta);
$em->persisty($pessoa);
$em->Flush();

What I’m looking for is a way to reference the entity account automatically, using something native to Doctrine, in the same way that Sqlfilter does in queries.

Does anyone know anything?

1 answer

0

After the persist Doctrine populates the entity id:

$em->persist($account);
$em->flush();
$account->getId();

The $account->getId() will return to you the generated id.

  • Thank you for answering. I edited the question to make the need clearer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.