1
0

More than 3 years have passed since last update.

PHP PhalconでAuto Increment付与のMigrationが動かない対応

Last updated at Posted at 2020-07-01

はじめに

PhalconにおいてMigrationで新テーブルをCreateする場合は普通に定義すればAuto Incrementは簡単につけられます。
本記事は、既存テーブルのKeyカラムにAuto IncrementをAlterで後から付けたかったが動かなかったので、その対応をしたという話です

最初は

普通に列変更でいけると思っていたので最初、up()に新、down()に旧をmorphTable()で書けばいいやとしてみました。

public function up()
{
    $this->morphTable('table_name', [
        'columns' => [
            new Column(
                'id',
                [
                    'type' => Column::TYPE_INTEGER,
                    'notNull' => true,
                    'autoIncrement' => true,
                    'size' => 11,
                    'first' => true
                ]
            ),

            /* 省略(その他のカラム情報) */
        ]
    ]);
}


public function down()
{
    $this->morphTable('table_name', [
        'columns' => [
            new Column(
                'id',
                [
                    'type' => Column::TYPE_INTEGER,
                    'notNull' => true,
                    'size' => 11,
                    'first' => true
                ]
            ),

ところが、これだとうまく動かない。
Migration自体の結果はsuccessとなるが、この例で言うidカラムのAlterを実行している形跡がないぞ、、と困ってしまいました

そこで

じゃあ明示的にSQL書いたりとかそういうのできないのかなと思って、ちょっと調べてみると、 self::$_connectionに、イケそうなMethodがあるではありませんか。
(そう言えばdropTableの時にいつも使っているやつだったな)
ということで

public function up()
{
    self::$connection->modifyColumn('table_name', null, new Column(
        'id',
        [
            'type' => Column::TYPE_INTEGER,
            'notNull' => true,
            'autoIncrement' => true,
            'size' => 11,
            'first' => true
        ]
    ));
}

できたやんけー。という感じでした。
加えてmorphTable()で記述していた時は、カラムが多い時に見づらくてちょっと不満があったのですが、この書き方だと純粋に変更箇所だけの記載になるので、これはこれでいいかもな。とも思ったのでした

1
0
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
1
0