LoginSignup
2
5

More than 5 years have passed since last update.

FuelPHPではcreated_at、updated_atがintegerなので注意! そして カラム変更のマイグレーションを試す

Last updated at Posted at 2015-09-13

はじめに

http://qiita.com/ms2sato/items/d678997709e6a388149f
で、簡単にFuelPHPを試してみたのですが、よく見たらcreated_atupdated_atの型がintegerでした。これは困るので修正をします。

Migrationファイルが作成できない??

migrationファイルをコマンドで作成してゴニョゴニョしたいと思ったのですが、generate出来ない問題にハマりました(未解決)。

oil g migration rename_created_at_to_test_in_threads
Uncaught exception Exception: No migration could be generated. Please verify your command syntax.
Callstack: 
#0 [internal function]: Oil\Generate::migration(Array)
#1 /Users/ms2/dev/samples/fuelsample/fuel/packages/oil/classes/command.php(69): call_user_func('Oil\\Generate::m...', Array)
#2 /Users/ms2/dev/samples/fuelsample/oil(68): Oil\Command::init(Array)
#3 {main}

テーブルのcreate等はできるので、コマンドによるのでしょうか。どうもダメそうなので、雛形を作るのみにして、名前変更&中身修正してしまいました。
http://fuelphp.jp/docs/1.7/packages/oil/generate.html#/magic_migrations が参考になるかと思ったのですが、create以外はエラーに成ってしまう模様。。

そして、migrationのファイルはDBUtilというクラスのメソッドを呼び出してやる様子なので、下記を参照。
http://fuelphp.jp/docs/1.7/classes/database/dbutil.html

Migration

結局私のところでは下記のようなマイグレーションファイルを作成しました。

fuel/app/migrations/002_created_at_and_updated_at_arrange_in_threads.php
<?php

namespace Fuel\Migrations;

class Created_at_and_updated_at_arrange_in_threads
{
    public function up()
    {
        \DBUtil::modify_fields('threads', [
            'created_at' => ['type' => 'timestamp', 'null' => true],
            'updated_at' => ['type' => 'timestamp', 'null' => true]
        ]);
    }

    public function down()
    {
        \DBUtil::modify_fields('threads', [
            'created_at' => ['constraint' => 11, 'type' => 'int', 'null' => true],
            'updated_at' => ['constraint' => 11, 'type' => 'int', 'null' => true]
        ]);
    }
}

あとは

oil refine migrate

すれば無事にDBの内容は変更されました!Good!

コードの変更

モデルも変更します。'mysql_timestamp' => true に揃えましょう。

    protected static $_observers = array(
        'Orm\Observer_CreatedAt' => array(
            'events' => array('before_insert'),
            'mysql_timestamp' => true,
        ),
        'Orm\Observer_UpdatedAt' => array(
            'events' => array('before_save'),
            'mysql_timestamp' => true,
        ),
    );

これで修正は終わりです!ちゃんとtimestampで時刻が入ると思います!

おしまいに

本当はmigrationのファイルを作成するときにオプションを指定するようです。うーん、この仕様は微妙な感じです。デフォルトで日時の型になるようにした方が良いと思うのですが。
http://fuelphp.jp/docs/1.6/packages/oil/generate.html#/timestamp_fields

php oil g model thread title:varchar[255] body:text --mysql-timestamp 

今回の対応の内容はこちら。
https://github.com/ms2sato/fuelsample/commit/1adb83f034a2ccd705e8b6bf0ad02b7562b525c3

2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5