0

I'm building a project using Doctrine 2 to interact with my database (I'm usign postgres).

For one of my entities I need to have a field that, on insert, is populated using a postgres function.

Is there a way to this with Doctrine? Is there an annotation to specify this? Otherwise, is there a way to override the query made when performing the database insert?

marcosh
  • 8,780
  • 5
  • 44
  • 74
  • 1
    Lifecycle events http://doctrine-orm.readthedocs.org/en/latest/reference/events.html#reference-events-lifecycle-events – JimL Oct 04 '15 at 17:15
  • @JimL thanks, I guess I'll have to attach to the prePersist event. But how can I edit the INSERT query performed on the database? – marcosh Oct 04 '15 at 17:26
  • just set $this->yourField = 'new value' and it will be inserted with the correct value. You can of course read $this->otherValue as a condition to which new value you should set. – JimL Oct 04 '15 at 17:27
  • @JimL I need to use a postgres function to set the new field value. If I use $this->myField = 'postgres_function()' I'm afraid Doctrine will consider it a string and not a postgres function – marcosh Oct 04 '15 at 17:31
  • There are three ways to do this. One is to have the ORM call the function, retrieve the value, and store it in the object before persisting it. Another way is to convince the ORM to leave the field unset - either explicitly `DEFAULT` in the `INSERT`, or omit the column from the `INSERT` entirely. The third is to get the ORM to add an expression calling the function into the `VALUES` clause, but I've never seen an ORM that easily supports that. – Craig Ringer Oct 05 '15 at 03:11
  • @CraigRinger thanks for your comment. What I'd like to achieve is what you propose in this answer: http://stackoverflow.com/a/9985219/2718064, so the third approach you propose here seems the best. At the same time, as you say, I think it won't be easy to implement using Doctrine – marcosh Oct 05 '15 at 06:13

0 Answers0