我想使用code
而不是控制台窗口来migrate
up
/down
数据库。我已经调查过framework
了。我已经尝试了以下代码:
$runner = new yii\console\Application([
'id' => 'auto-migrate',
'basePath' => dirname(__DIR__)
]);
$runner->runAction('migrate');
ob_start();
return htmlentities(ob_get_clean(), null, Yii::$app->charset);
它提供了Internal Server Error
。甚至不会将文件迁移到数据库中。但是如果该目录不存在,它就会创建该目录。它的行为是正常的,但是如果迁移文件存在于同一目录中,它将提供Internal Server Error
。
发布于 2015-10-16 15:21:01
\Yii::$app->runAction('migrate', ['migrationPath' => '@yii/rbac/migrations/']);
发布于 2018-03-28 10:48:39
您可以使用加载控制台配置来创建控制台应用程序来运行迁移:
public function actionMigrate()
{
// Keep current application
$oldApp = \Yii::$app;
// Load Console Application config
$config = require \Yii::getAlias('@app'). '/config/console.php';
new \yii\console\Application($config);
$result = \Yii::$app->runAction('migrate', ['migrationPath' => '@app/migrations/', 'interactive' => false]);
// Revert application
\Yii::$app = $oldApp;
return;
}
上面的示例代码是针对is i2-app-basic模板的,您可以更改is i2-app-advanced模板的路径。
发布于 2018-06-30 00:20:27
对于这样的情况,我使用这个解决方案。我只实现了migrate/up
的情况。要执行任何其他migrate
命令,您必须配置runAction()
的参数。
use yii\console\controllers\MigrateController;
/*Suppose that config is an array with the following structure
[
'class' => 'yii\db\Connection',
'dsn' => "$dsn",
'username' => "$username",
'password' => "$password",
'charset' => 'utf8',
]
*/
public function migrateUp($config){
$migrate = new MigrateController('migrate', \Yii::$app);
/*The name of the table for keeping applied migration information*/
$migrate->migrationTable = 'migration';
/*At least one of `migrationPath` or `migrationNamespaces` should be specified.
For this example I use `migrationNamespaces` to find a specific set of migrations I want to execute.*/
$migrate->migrationNamespaces = [
'app\modules\v1\migrations'
];
$migrate->migrationPath = null;
/*The DB connection object to use when applying migrations*/
$migrate->db = $config;
/*Run migrations without asking questions*/
$migrate->interactive = false;
/*The individual commands ran within the migration will not be output to the console*/
$migrate->compact = true;
/*php://temp is a read-write stream that allow temporary data to be stored in a file-like wrapper */
define('STDOUT', $fp= fopen('php://temp', 'r+'));
/*run migrate/up */
$status = $migrate->runAction('up');
/*Rewind the position of the file pointer*/
rewind($fp);
$migrationOutput = stream_get_contents($fp);
if (isset($status)){
ob_get_clean();
return ['Errors when executing migrations', $migrationOutput];
}
return ['Everything ok', $migrationOutput];
}
https://stackoverflow.com/questions/28260014
复制相似问题