Mysql不允许在同一数据库表中自动更新两个时间戳列。然而,许多人喜欢为他们的表“创建”和“更新”列,因为这类信息很有用,所以必须做一些工作。根据我收集的信息,一列必须是日期时间,另一列必须是时间戳。datetime列可以用作创建的列,当缺省为null时,在使用触发器插入时,它将自动获取当前的时间戳值。timestamp列可以用作更新列,并且可以按照mysql文档的描述配置为自动更新。这两个页面对于理解这一点很有用:
Mysql Datetime and Timestamp Types
Auto Initialization and Updated for Timestamp
棘手之处在于使用drupal的模式函数实现这一点。有没有人在Drupal7中找到了成功的解决方案?
发布于 2013-07-16 10:18:26
在玩弄了语法和许多其他堆栈溢出问题/答案的不同建议之后,我终于找到了正确的小代码添加组合,以便在我的数据库表中自动“创建”和“更新”列。
在我的hook_schema()函数中:
$schema['table'] = array(
'fields' => array(
'created' => array(
'mysql_type' => 'datetime',
'not null ' => TRUE,
'default' => format_date(time(), 'custom', 'Y-m-d 00:00:00'),
),
'updated' => array(
'mysql_type' => 'timestamp',
'not null' => TRUE,
),
),
//other parts of the schema (indexes, keys...)
);在我的hook_install()函数中:
//Automatically set created datetime for current timestamp upon insert
$query = db_query('
CREATE TRIGGER triggername BEFORE INSERT ON tablename FOR EACH ROW BEGIN SET
NEW.created=NOW(); END
');
//Automatically update 'updated' to current timestamp whenever a row is changed
$query = db_query('
ALTER TABLE tablename
MODIFY updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
');“触发器名称”是您想给触发器命名的任何名称。'tablename‘是您在hook_schema()中建立的表的名称,其中包含已创建和已更新的列。
希望这能对某些人有用。当我在几周前研究这个问题的时候,在drupal中没有人这样做的帖子,并且很难弄清楚如何使不同的建议适应drupal框架。这是我想出的最好的解决方案。如果你有另一篇你认为更好的文章,那就把它贴出来吧!
发布于 2015-02-12 02:44:05
扳机!谢谢!唯一一个在自己的模块里装了触发器的人。你救了我的命。
* Implementation of hook_install()
* @see http://api.drupal.org/api/function/hook_install/
* this is called when a module is installed, providing a chance
* to create any database tables specific our module
*/
function upgrade_inforegistration_install()
{
$query = db_query('
CREATE TRIGGER `mydb`.`mytriggername`
AFTER INSERT ON `mytrigtable`
FOR EACH ROW
BEGIN
INSERT INTO `mydb`.`myaffectedtable`
(`day`, `uid`, `anotherfield`)
VALUES (UNIX_TIMESTAMP(NOW()), NEW.uid, `1`);
END
');
}发布于 2017-01-19 18:17:10
function moduleName_schema() {
$schema['tableName'] = array(
'fields' => array(
'id' => array(
'type' => 'serial',
'not null' => TRUE,
),
'colName' => array(
'mysql_type' => 'timestamp',
'not null' => TRUE
),
....other fields..
....
),
'primary key' => array('id'),
);
return $schema;
}
function bd_contact_enable() {
db_query('
ALTER TABLE {bd_contact}
MODIFY created TIMESTAMP NOT NULL
DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP'
);
}将这两个方法写入moduleName.install文件。
如果您已经安装并重新安装,请卸载您的模块以查看效果。
我已经在Drupal8.2.3中检查过了,它工作正常。我对Drupal7不太确定。
当添加一行时,它将存储当前的日期时间(格式->2017-01-19 15:23:47),并将在该行获得更新时进行更新。
https://stackoverflow.com/questions/17657401
复制相似问题