はじめに
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()
で記述していた時は、カラムが多い時に見づらくてちょっと不満があったのですが、この書き方だと純粋に変更箇所だけの記載になるので、これはこれでいいかもな。とも思ったのでした