Yii 2.0: Execute migration on server/linux using shell


It's easy to execute migration locally on XAMPP using cmd, but on server where you script is it's little bit harder.

I use Linux server with cPanel. I wanted to execute migration for yii2-user. This is how I did it.

This is how you do it. Put your file, for example: migration.php in your root folder: migration.php

Put this code inside:

$output = exec('yes | php yii migrate/up --migrationPath=@vendor/dektrium/yii2-user/migrations');
echo "<pre>$output</pre>";

Let me explain what it does:

exec - executes shell command

php yii migrate/up - executes command for migration, see details here (http://www.yiiframework.com/doc-2.0/guide-db-migrations.html)

--migrationPath=@vendor/dektrium/yii2-user/migrations - this is migration path, where migrations files I want to execute are located.

| - pipe, connecting second command with first

yes - after command:

php yii migrate/up --migrationPath=@vendor/dektrium/yii2-user/migrations

is executed, it will ask you:

Apply the above migrations? (yes|no) [no]

But since you cannot confirm or reject because you are executing php file you put "yes" before that command and it knows that after executing main command it has to confirm. You can put "no" instead.

Before executing file on your server, do it locally on your laptop using XAMPP to test it and see output.

This is working:

exec('yes | php yii migrate/up --migrationPath=@vendor/dektrium/yii2-user/migrations')

but I guess this would work also, I didn't test this one:

exec('php yii migrate/up --migrationPath=@vendor/dektrium/yii2-user/migrations | yes')

Total 2 comments

#19615 report it
bmsrox at 2015/10/03 12:20pm
Use --interactive=0

exec('php yii migrate/up --interactive=0 --migrationPath=@vendor/dektrium/yii2-user/migrations')

#19614 report it
Artur Oliveira at 2015/10/03 08:25am
Interactive flag vs echo yes -

Have you tried using the interactive flag instead of piping the yes

Using Command Line Options

The migration command comes with a few command-line options that can be used to customize its behaviors:

interactive: boolean (defaults to true), specifies whether to perform migrations in an interactive mode. When this is true, the user will be prompted before the command performs certain actions. You may want to set this to false if the command is being used in a background process.

From: http://www.yiiframework.com/doc-2.0/guide-db-migrations.html

Leave a comment

Please to leave your comment.

Write new article