Starting from version v2.8, if the time fields created_at, updated_at, and deleted_at are Boolean fields, the ORM component will automatically recognize and support them, writing Boolean type values (represented by 0 and 1). Typically, the Boolean field is the deleted_at field, and we only demonstrate the case where the deleted_at field is of type bool.

Example SQL

This is the MySQL table structure used in the example code that follows.

  1. CREATE TABLE `user` (
  2. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  3. `name` varchar(45) NOT NULL,
  4. `status` tinyint DEFAULT 0,
  5. `created_at` int(10) unsigned DEFAULT NULL,
  6. `updated_at` int(10) unsigned DEFAULT NULL,
  7. `deleted_at` bit(1) DEFAULT NULL,
  8. PRIMARY KEY (`id`)
  9. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

We recommend using bit(1) to represent the bool type for the field instead of tinyint(1) or int(1) because the range of tinyint(1)/int(1) is -127~127, which is often used as a status field type. The range of bit(1) is 0/1, which can effectively represent the two values false/true of the bool type.

Time Fields - Boolean Fields - 图1tip

If you try to test and view the ORM operation execution SQL statements, it is recommended to enable the debug mode (related documentation: ORM Senior - Debug Mode), and the SQL statements will be automatically printed to the log output.

created_at Write Time

  1. // INSERT INTO `user`(`name`,`created_at`,`updated_at`,`deleted_at`) VALUES('john',1731481488,1731481488,0)
  2. g.Model("user").Data(g.Map{"name": "john"}).Insert()

deleted_at Data Soft Deletion

  1. // UPDATE `user` SET `deleted_at`=1 WHERE (`id`=10) AND `deleted_at`=0
  2. g.Model("user").Where("id", 10).Delete()

Some changes occur during the query, for example:

  1. // SELECT * FROM `user` WHERE (id>1) AND `deleted_at`=0
  2. g.Model("user").Where("id>?", 1).All()