date字段中的current_timestamp


8

如何在drupal数据库架构中为date feild添加current_timestamp或now。

        'created' => array(
            'description' => t('Timestamp when the fee schedule was added.'),
            'type' => 'int',
            'not null' => TRUE,
            'unsigned' => TRUE,
        ),

1
我在user.module上进行了搜索。Drupal正在保存创建的内容,例如$ array ['created'] = time();
niksmac 2012年

Answers:


6

您可以使用mysql_type属性为MySQL指定特定于驱动程序的列类型:

function MYMODULE_schema (){
  $schema['table_name'] = array(
    'fields' => array(
      'created' => array(
        'mysql_type' => 'timestamp',
        'not null' => TRUE
      )
    )
  );

  return $schema;
}

然后,在启用模块时,您只需修改该列即可添加默认/更新行为:

function MYMODULE_enable() {
  db_query('
    ALTER TABLE {table_name} 
    MODIFY created TIMESTAMP NOT NULL 
    DEFAULT CURRENT_TIMESTAMP 
    ON UPDATE CURRENT_TIMESTAMP'
  );
}

我刚刚在Drupal 7上对其进行了测试,并且可以正常工作。

注意:如果您不希望每次记录更新时都更新时间戳,则只需删除ON UPDATE CURRENT_TIMESTAMP查询的一部分。


1

我假设您指的是MySQL,您想直接从文档中了解的功能是时间戳

这可能会将由架构创建的数据库表更新为您要查找的字段类型:

MODIFY COLUMN `created` TIMESTAMP NOT NULL DEFAULT current_timestamp;

刚偶然发现 这篇文章中,Drupal 8应该支持时间戳,所以我认为(我认为是错误的)D7可能不被支持。只需在您的数组中将类型更改为TIMESTAMP,然后看看会产生什么,但我不会通过D7模式api进行任何操作。

更新:

实际上,请看一下帖子。该补丁将为D7中的时间戳添加支持。Drupalshrek的主要荣誉与我们一起分享这一点。

数据库模式一旦修补,将如下所示:

<?php
$schema['vchess_moves'] = array(
  'description' => 'Contains the list of moves for each game',
  'fields' => array(
    'timestamp' => array(
    'description' => 'Exact date and time of the move',
    'type' => 'timestamp',
    'not null' => TRUE,
?>

去看上面的补丁补丁,我不会在这里重新发布他的东西,不确定这样做是否合适。

希望对您有所帮助,祝您编程愉快。


0

这是Drupal 8.6.x的解决方案,以防万一有人正在照我的样子:)

'created' => [
  'mysql_type' => 'timestamp',
  'not null' => TRUE,
  'mysql_default' => CURRENT_TIMESTAMP,
 ],

这相当于...

`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.