1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

cakephp3のマイグレーションファイル内でDB接続先を変えれるか

Last updated at Posted at 2018-08-23

結論

接続先別にディレクトリを分けてコマンド叩くときにオプション指定する
CakePHP3のMigrationsでDB接続先を切り替える方法

試したこと

<?php
use Migrations\AbstractMigration;
use Cake\Datasource\ConnectionManager;
use \Phinx\Db\Adapter\MysqlAdapter as MysqlAdapter;

class CreateUsers extends AbstractMigration
{
    public function initialize()
    {
        $connectionArray = ConnectionManager::get('other')->config();
        $connectionArray['pass'] = $connectionArray['password'];
        $connectionArray['user'] = $connectionArray['username'];
        $connectionArray['name'] = $connectionArray['database'];
        $this->setAdapter(new MysqlAdapter($connectionArray));
    }
    public function change()
    {
        $this->initialize();

        $table = $this->table('users', ['id' => false, 'primary_key' => ['user_id']]);
        $table->addColumn('user_id', 'biginteger', [
            'autoIncrement' => true,
            'comment' => 'ID',
            'default' => null,
            'limit' => 20,
            'null' => false,
        ]);
        $table->create();
    }
}

上記のファイルで下記コマンドをたたけば一応振り分けてくれた。
./bin/cake migrations migrate

が、defaultDBとotherDBの両方にphinxlogが出来てしまった。
defaultDB側のphinxlogに実行したログが残り、statusがupとなる。
otherDB側のphinxlogは空だが、tableはこちらのDBに作られた。
もやもやするので却下。

※別の方法があれば追記予定

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?