We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Weird problem with a model "created_at" field.

Hi, I'm getting a problem with my "created_at" field.

CREATE TABLE `posts` (
  `title_id` bigint(20) unsigned NOT NULL,
  `episode_id` bigint(20) unsigned DEFAULT NULL,
  `lang_id` int(11) unsigned NOT NULL DEFAULT '0',
  `file` mediumtext NOT NULL,
  `uploaded_by` bigint(20) unsigned DEFAULT NULL,
  `verified_by` bigint(20) unsigned DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `id` bigint(11) DEFAULT NULL,
  PRIMARY KEY (`title_id`,`lang_id`),
  KEY `lang_id` (`lang_id`),
  KEY `uploaded_by` (`uploaded_by`),
  KEY `verified_by` (`verified_by`),
  KEY `episode_id` (`episode_id`),
  CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`title_id`) REFERENCES `titles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `posts_ibfk_2` FOREIGN KEY (`lang_id`) REFERENCES `languages` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `postss_ibfk_3` FOREIGN KEY (`uploaded_by`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `posts_ibfk_4` FOREIGN KEY (`verified_by`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `posts_ibfk_5` FOREIGN KEY (`episode_id`) REFERENCES `episodes` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Inside my model:

    public function beforeCreate()
    {
        $this->created_at = date("Y-m-d H:i:s");
    }

Error on save: "created_at is required"



85.5k

because created_at is not null, some orm configs might fix it, i personally removed the not null myself, even tho its not exactly a correct thing to do

phalcon orm, validates data with mysql types and sizes before saving it. You can pass created_at to the data manually before ->save()



93.7k
Accepted
answer

Either @Izo solution or change beforeCreate to beforeValidationOnCreate(). You need to set the default value BEFORE THE VALIDATION, beforeCreate means do something AFTER validation, but BEFORE insert.



85.5k

now that i did not know. nice

For some reason I was unable to comment. So, I tried all the solutions you pointed out. But the only way I could sove was removing "RIMARY KEY (title_id,lang_id)," and creating a auto_increment id



85.5k

removing that primary key doesnt seem to be linked with the issue you said ( at least with what I can see )

I also faced this same problem with the createdAt field wgich is not null. My solution was using beforeValidationOnCreate() instead of beforeCreate(). Also did the same for my updatedAt field , update though...