CakePHP+MySQLのcreatedとmodifiedについて

CakePHP+MySQLでフィールドをcreatedとmodifiedの型指定について勉強になった部分があったのでメモとして残す。まず、CakePHPにおけるcreatedとmodifiedについて

 

 

Saving Your Data — CakePHP Cookbook 2.x documentation

By defining a created and/or modified field in your database table as datetime fields (default null), CakePHP will recognize those fields and populate them automatically whenever a record is created or saved to the database (unless the data being saved already contains a value for these fields).

 

The created and modified fields will be set to the current date and time when the record is initially added. The modified field will be updated with the current date and time whenever the existing record is saved.

 

テーブルのカラムの中でcreatedとmodifiedというフィールドを定義しておくとcreatedについては、最初のデータ挿入段階でmodifiedについては、データの更新時に現在の日時を自動的に挿入してくれる。

この中で、自分がはまってしまったのが"createdとmodifiedのカラムの型をdatetimeに指定し、デフォルトをnullにする事"であった。

createdとmodifiedのカラムをdatetime型にしなければいけないという点に気づくまでは、型をtimestampに指定してカラムを作成していた。

MySQLWorkbenchでは、作成出来たのでそのまま実装していた。しかし、データベースサーバを移行させようとmysqldumpコマンドでdumpを取得し新規に立てたデータベースサーバにインポート使用とした時に

f:id:umadanshaku:20150606185916p:plain

TIMESTAMP型のカラムでCURRENT_TIMESTAMPがデフォルトであるものは、1つしか指定できませんというエラーで怒られる。(ERROR 1293:Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause)MySQLってこんな仕様なんだっけといろいろwebで調べてみたらいっぱい出てきてどうやらそのような感じであった。公式ドキュメントを調べてみると

 

MySQL :: MySQL 5.0 Reference Manual :: 11.3.5 Automatic Initialization and Updating for TIMESTAMP

One TIMESTAMP column in a table can have the current timestamp as the default value for initializing the column, as the auto-update value, or both. It is not possible to have the current timestamp be the default value for one column and the auto-update value for another column.

どうやら複数カラム指定した事が仕様と合っていないらしい。

 

対策として

カラムの型をTIMESTAMPからdatetimeに変更しデフォルトをNULLに設定する事で解決した。

◆変更前

  `created` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  `modified` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

◆変更後

  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,