Doctrine: Set CURRENT_TIMESTAMP as default value by the database (i.e. not by PHP)











up vote
0
down vote

favorite












After looking around for a while, I still couldn't find a way to get CURRENT_TIMESTAMP inserted by the database server (as default value on INSERT).



The problem: When you persist an object to the database, missing fields are explicitly set to NULL by Doctrine. So it looks like, setting a default value in the table definition, doesn't have any effect at all :-(



I don't want to set the time through PHP (e.g. $object->setTimestamp(new DateTime());) cause this might return a different time than what the database server has, as explained here: https://stackoverflow.com/a/3705090/1668200



What I've tried so far:




  • Send in NOW literally (e.g. $object->setTimestamp('NOW()');), as explained here: https://stackoverflow.com/a/13850741/1668200

    => Didn't work: Error: Call to a member function format() on string


  • Removing the 'timestamp' property from the object just before persisting it (see https://stackoverflow.com/a/3600758/1668200 ) didn't work either: The field was set to NULL by Doctrine anyway.



Any other solution I found (including the Doctrine extension 'Timestampable' https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/timestampable.md ) uses PHP's time.










share|improve this question




























    up vote
    0
    down vote

    favorite












    After looking around for a while, I still couldn't find a way to get CURRENT_TIMESTAMP inserted by the database server (as default value on INSERT).



    The problem: When you persist an object to the database, missing fields are explicitly set to NULL by Doctrine. So it looks like, setting a default value in the table definition, doesn't have any effect at all :-(



    I don't want to set the time through PHP (e.g. $object->setTimestamp(new DateTime());) cause this might return a different time than what the database server has, as explained here: https://stackoverflow.com/a/3705090/1668200



    What I've tried so far:




    • Send in NOW literally (e.g. $object->setTimestamp('NOW()');), as explained here: https://stackoverflow.com/a/13850741/1668200

      => Didn't work: Error: Call to a member function format() on string


    • Removing the 'timestamp' property from the object just before persisting it (see https://stackoverflow.com/a/3600758/1668200 ) didn't work either: The field was set to NULL by Doctrine anyway.



    Any other solution I found (including the Doctrine extension 'Timestampable' https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/timestampable.md ) uses PHP's time.










    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      After looking around for a while, I still couldn't find a way to get CURRENT_TIMESTAMP inserted by the database server (as default value on INSERT).



      The problem: When you persist an object to the database, missing fields are explicitly set to NULL by Doctrine. So it looks like, setting a default value in the table definition, doesn't have any effect at all :-(



      I don't want to set the time through PHP (e.g. $object->setTimestamp(new DateTime());) cause this might return a different time than what the database server has, as explained here: https://stackoverflow.com/a/3705090/1668200



      What I've tried so far:




      • Send in NOW literally (e.g. $object->setTimestamp('NOW()');), as explained here: https://stackoverflow.com/a/13850741/1668200

        => Didn't work: Error: Call to a member function format() on string


      • Removing the 'timestamp' property from the object just before persisting it (see https://stackoverflow.com/a/3600758/1668200 ) didn't work either: The field was set to NULL by Doctrine anyway.



      Any other solution I found (including the Doctrine extension 'Timestampable' https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/timestampable.md ) uses PHP's time.










      share|improve this question















      After looking around for a while, I still couldn't find a way to get CURRENT_TIMESTAMP inserted by the database server (as default value on INSERT).



      The problem: When you persist an object to the database, missing fields are explicitly set to NULL by Doctrine. So it looks like, setting a default value in the table definition, doesn't have any effect at all :-(



      I don't want to set the time through PHP (e.g. $object->setTimestamp(new DateTime());) cause this might return a different time than what the database server has, as explained here: https://stackoverflow.com/a/3705090/1668200



      What I've tried so far:




      • Send in NOW literally (e.g. $object->setTimestamp('NOW()');), as explained here: https://stackoverflow.com/a/13850741/1668200

        => Didn't work: Error: Call to a member function format() on string


      • Removing the 'timestamp' property from the object just before persisting it (see https://stackoverflow.com/a/3600758/1668200 ) didn't work either: The field was set to NULL by Doctrine anyway.



      Any other solution I found (including the Doctrine extension 'Timestampable' https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/timestampable.md ) uses PHP's time.







      php symfony doctrine2






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited May 23 '17 at 12:25









      Community

      11




      11










      asked Aug 11 '15 at 16:38









      Thomas Landauer

      2,25811646




      2,25811646
























          3 Answers
          3






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          Have a look at this: https://stackoverflow.com/a/29384596/3255540 it should resolve the problem with Error: Call to a member function format() on string and force SQL NOW() to be sent to the database.






          share|improve this answer



















          • 1




            Oh, I see. Sorry for misunderstanding. Did you experiment with this:http://stackoverflow.com/a/29384596/3255540 could resolve the problem with Error: Call to a member function format() on string and force NOW() to database.
            – Jan Mares
            Feb 16 '16 at 10:48












          • I am glad to help. I edited the answer, could you accept it?
            – Jan Mares
            Feb 24 '16 at 17:16


















          up vote
          0
          down vote













          UPDATE: This is not compatible with VasekPurchartDoctrineDateTimeImmutableTypesBundle anymore. And it won't work with Doctrine DBAL 2.6. See https://github.com/VasekPurchart/Doctrine-Date-Time-Immutable-Types-Bundle/issues/17





          So, wrapping it all up, here's a step-by-step instruction:



          1) Create a new Class "DateTimeNow"; a good location is probably AppBundle/Entity/DateTimeNow.php:



          <?php
          namespace AppBundleEntity;
          class DateTimeNow
          {
          public function format()
          {
          return 'NOW()';
          }
          }


          2) In your to-be-timestamped entity, add a function to be executed whenever a new entity is saved (i.e. on each INSERT):



          public function doPrePersist()
          {
          $this->timestamp = new DateTimeNow();
          }


          3) Register this function as a Lifecycle Callback prePersist. For Annotations, see http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/annotations-reference.html#annref-prepersist. For YAML:



          AppBundleEntityWhatever:
          # ...
          lifecycleCallbacks:
          prePersist: [ doPrePersist ]


          That's it! :-)



          Now, when you persist an empty object, this is the resulting query:



          INSERT INTO public.whatever(id, text, timestamp) VALUES (?, ?, ?)
          Parameters: { 1: null, 2: null, 3: NOW() }





          share|improve this answer






























            up vote
            0
            down vote













            /**
            * @ORMColumn(type="datetime", options={"default": "CURRENT_TIMESTAMP"})
            */
            protected $created;


            Just remember that this will not allow previous rows to be empty if you update an existing table.






            share|improve this answer





















              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f31947364%2fdoctrine-set-current-timestamp-as-default-value-by-the-database-i-e-not-by-ph%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              0
              down vote



              accepted










              Have a look at this: https://stackoverflow.com/a/29384596/3255540 it should resolve the problem with Error: Call to a member function format() on string and force SQL NOW() to be sent to the database.






              share|improve this answer



















              • 1




                Oh, I see. Sorry for misunderstanding. Did you experiment with this:http://stackoverflow.com/a/29384596/3255540 could resolve the problem with Error: Call to a member function format() on string and force NOW() to database.
                – Jan Mares
                Feb 16 '16 at 10:48












              • I am glad to help. I edited the answer, could you accept it?
                – Jan Mares
                Feb 24 '16 at 17:16















              up vote
              0
              down vote



              accepted










              Have a look at this: https://stackoverflow.com/a/29384596/3255540 it should resolve the problem with Error: Call to a member function format() on string and force SQL NOW() to be sent to the database.






              share|improve this answer



















              • 1




                Oh, I see. Sorry for misunderstanding. Did you experiment with this:http://stackoverflow.com/a/29384596/3255540 could resolve the problem with Error: Call to a member function format() on string and force NOW() to database.
                – Jan Mares
                Feb 16 '16 at 10:48












              • I am glad to help. I edited the answer, could you accept it?
                – Jan Mares
                Feb 24 '16 at 17:16













              up vote
              0
              down vote



              accepted







              up vote
              0
              down vote



              accepted






              Have a look at this: https://stackoverflow.com/a/29384596/3255540 it should resolve the problem with Error: Call to a member function format() on string and force SQL NOW() to be sent to the database.






              share|improve this answer














              Have a look at this: https://stackoverflow.com/a/29384596/3255540 it should resolve the problem with Error: Call to a member function format() on string and force SQL NOW() to be sent to the database.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited May 23 '17 at 12:31









              Community

              11




              11










              answered Feb 15 '16 at 16:09









              Jan Mares

              464513




              464513








              • 1




                Oh, I see. Sorry for misunderstanding. Did you experiment with this:http://stackoverflow.com/a/29384596/3255540 could resolve the problem with Error: Call to a member function format() on string and force NOW() to database.
                – Jan Mares
                Feb 16 '16 at 10:48












              • I am glad to help. I edited the answer, could you accept it?
                – Jan Mares
                Feb 24 '16 at 17:16














              • 1




                Oh, I see. Sorry for misunderstanding. Did you experiment with this:http://stackoverflow.com/a/29384596/3255540 could resolve the problem with Error: Call to a member function format() on string and force NOW() to database.
                – Jan Mares
                Feb 16 '16 at 10:48












              • I am glad to help. I edited the answer, could you accept it?
                – Jan Mares
                Feb 24 '16 at 17:16








              1




              1




              Oh, I see. Sorry for misunderstanding. Did you experiment with this:http://stackoverflow.com/a/29384596/3255540 could resolve the problem with Error: Call to a member function format() on string and force NOW() to database.
              – Jan Mares
              Feb 16 '16 at 10:48






              Oh, I see. Sorry for misunderstanding. Did you experiment with this:http://stackoverflow.com/a/29384596/3255540 could resolve the problem with Error: Call to a member function format() on string and force NOW() to database.
              – Jan Mares
              Feb 16 '16 at 10:48














              I am glad to help. I edited the answer, could you accept it?
              – Jan Mares
              Feb 24 '16 at 17:16




              I am glad to help. I edited the answer, could you accept it?
              – Jan Mares
              Feb 24 '16 at 17:16












              up vote
              0
              down vote













              UPDATE: This is not compatible with VasekPurchartDoctrineDateTimeImmutableTypesBundle anymore. And it won't work with Doctrine DBAL 2.6. See https://github.com/VasekPurchart/Doctrine-Date-Time-Immutable-Types-Bundle/issues/17





              So, wrapping it all up, here's a step-by-step instruction:



              1) Create a new Class "DateTimeNow"; a good location is probably AppBundle/Entity/DateTimeNow.php:



              <?php
              namespace AppBundleEntity;
              class DateTimeNow
              {
              public function format()
              {
              return 'NOW()';
              }
              }


              2) In your to-be-timestamped entity, add a function to be executed whenever a new entity is saved (i.e. on each INSERT):



              public function doPrePersist()
              {
              $this->timestamp = new DateTimeNow();
              }


              3) Register this function as a Lifecycle Callback prePersist. For Annotations, see http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/annotations-reference.html#annref-prepersist. For YAML:



              AppBundleEntityWhatever:
              # ...
              lifecycleCallbacks:
              prePersist: [ doPrePersist ]


              That's it! :-)



              Now, when you persist an empty object, this is the resulting query:



              INSERT INTO public.whatever(id, text, timestamp) VALUES (?, ?, ?)
              Parameters: { 1: null, 2: null, 3: NOW() }





              share|improve this answer



























                up vote
                0
                down vote













                UPDATE: This is not compatible with VasekPurchartDoctrineDateTimeImmutableTypesBundle anymore. And it won't work with Doctrine DBAL 2.6. See https://github.com/VasekPurchart/Doctrine-Date-Time-Immutable-Types-Bundle/issues/17





                So, wrapping it all up, here's a step-by-step instruction:



                1) Create a new Class "DateTimeNow"; a good location is probably AppBundle/Entity/DateTimeNow.php:



                <?php
                namespace AppBundleEntity;
                class DateTimeNow
                {
                public function format()
                {
                return 'NOW()';
                }
                }


                2) In your to-be-timestamped entity, add a function to be executed whenever a new entity is saved (i.e. on each INSERT):



                public function doPrePersist()
                {
                $this->timestamp = new DateTimeNow();
                }


                3) Register this function as a Lifecycle Callback prePersist. For Annotations, see http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/annotations-reference.html#annref-prepersist. For YAML:



                AppBundleEntityWhatever:
                # ...
                lifecycleCallbacks:
                prePersist: [ doPrePersist ]


                That's it! :-)



                Now, when you persist an empty object, this is the resulting query:



                INSERT INTO public.whatever(id, text, timestamp) VALUES (?, ?, ?)
                Parameters: { 1: null, 2: null, 3: NOW() }





                share|improve this answer

























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  UPDATE: This is not compatible with VasekPurchartDoctrineDateTimeImmutableTypesBundle anymore. And it won't work with Doctrine DBAL 2.6. See https://github.com/VasekPurchart/Doctrine-Date-Time-Immutable-Types-Bundle/issues/17





                  So, wrapping it all up, here's a step-by-step instruction:



                  1) Create a new Class "DateTimeNow"; a good location is probably AppBundle/Entity/DateTimeNow.php:



                  <?php
                  namespace AppBundleEntity;
                  class DateTimeNow
                  {
                  public function format()
                  {
                  return 'NOW()';
                  }
                  }


                  2) In your to-be-timestamped entity, add a function to be executed whenever a new entity is saved (i.e. on each INSERT):



                  public function doPrePersist()
                  {
                  $this->timestamp = new DateTimeNow();
                  }


                  3) Register this function as a Lifecycle Callback prePersist. For Annotations, see http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/annotations-reference.html#annref-prepersist. For YAML:



                  AppBundleEntityWhatever:
                  # ...
                  lifecycleCallbacks:
                  prePersist: [ doPrePersist ]


                  That's it! :-)



                  Now, when you persist an empty object, this is the resulting query:



                  INSERT INTO public.whatever(id, text, timestamp) VALUES (?, ?, ?)
                  Parameters: { 1: null, 2: null, 3: NOW() }





                  share|improve this answer














                  UPDATE: This is not compatible with VasekPurchartDoctrineDateTimeImmutableTypesBundle anymore. And it won't work with Doctrine DBAL 2.6. See https://github.com/VasekPurchart/Doctrine-Date-Time-Immutable-Types-Bundle/issues/17





                  So, wrapping it all up, here's a step-by-step instruction:



                  1) Create a new Class "DateTimeNow"; a good location is probably AppBundle/Entity/DateTimeNow.php:



                  <?php
                  namespace AppBundleEntity;
                  class DateTimeNow
                  {
                  public function format()
                  {
                  return 'NOW()';
                  }
                  }


                  2) In your to-be-timestamped entity, add a function to be executed whenever a new entity is saved (i.e. on each INSERT):



                  public function doPrePersist()
                  {
                  $this->timestamp = new DateTimeNow();
                  }


                  3) Register this function as a Lifecycle Callback prePersist. For Annotations, see http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/annotations-reference.html#annref-prepersist. For YAML:



                  AppBundleEntityWhatever:
                  # ...
                  lifecycleCallbacks:
                  prePersist: [ doPrePersist ]


                  That's it! :-)



                  Now, when you persist an empty object, this is the resulting query:



                  INSERT INTO public.whatever(id, text, timestamp) VALUES (?, ?, ?)
                  Parameters: { 1: null, 2: null, 3: NOW() }






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jan 12 '17 at 10:24

























                  answered Jun 20 '16 at 14:06









                  Thomas Landauer

                  2,25811646




                  2,25811646






















                      up vote
                      0
                      down vote













                      /**
                      * @ORMColumn(type="datetime", options={"default": "CURRENT_TIMESTAMP"})
                      */
                      protected $created;


                      Just remember that this will not allow previous rows to be empty if you update an existing table.






                      share|improve this answer

























                        up vote
                        0
                        down vote













                        /**
                        * @ORMColumn(type="datetime", options={"default": "CURRENT_TIMESTAMP"})
                        */
                        protected $created;


                        Just remember that this will not allow previous rows to be empty if you update an existing table.






                        share|improve this answer























                          up vote
                          0
                          down vote










                          up vote
                          0
                          down vote









                          /**
                          * @ORMColumn(type="datetime", options={"default": "CURRENT_TIMESTAMP"})
                          */
                          protected $created;


                          Just remember that this will not allow previous rows to be empty if you update an existing table.






                          share|improve this answer












                          /**
                          * @ORMColumn(type="datetime", options={"default": "CURRENT_TIMESTAMP"})
                          */
                          protected $created;


                          Just remember that this will not allow previous rows to be empty if you update an existing table.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 9 at 11:04









                          Jørgen Rudolph Låker

                          514




                          514






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.





                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                              Please pay close attention to the following guidance:


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f31947364%2fdoctrine-set-current-timestamp-as-default-value-by-the-database-i-e-not-by-ph%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              這個網誌中的熱門文章

                              Xamarin.form Move up view when keyboard appear

                              Post-Redirect-Get with Spring WebFlux and Thymeleaf

                              Anylogic : not able to use stopDelay()