即今天新建了项目之后,继续玩了下新建的项目,开始遇到一个令人无语的问题,链接不上数据库,一直报PDO链接错误,惊讶之余发现旧项目是可以的,于是对比发现,默认的链接数据库的时候的服务器地址是localhost,但是!很坑,这里必须写IP。改成127.0.0.1就好了。 好吧,链接好数据库之后可以搞事情啦~没有数据库的要简单测试最简单的就是利用migrate迁移一个示例用的表出来,这个部分自己真心用的有点少
首先,我们为什么需要migrations,PHP自身是没有一种机制把项目最新的DB结构同时同步到不同的机器上.很多时候我们是卸掉原来的DB结构再把最新的DB结构导进来.如果某人修改了数据库结构,那么我们不得不把修改的SQL文件在所有不同的机器上跑一遍.而且这个修改者可能要一个一个得通知到所有人,或者把文件保留下来.一般到处或者数据库工具直接操作的时候会将与新建的同名表直接替换掉。那下面就来简单整理下YII下使用migrate:
安装好yii2后,Windows下运行cmd命令行,到yii2所在目录,输入以下命令,可以执行migration命令初始化数据表的程序,自动创建表:
一:看下已经有的文件~
<?php
use yii\db\Migration;
class m130524_201442_init extends Migration
{
public function up()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
// http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
$this->createTable('{{%user}}', [
'id' => $this->primaryKey(),
'username' => $this->string()->notNull()->unique(),
'auth_key' => $this->string(32)->notNull(),
'password_hash' => $this->string()->notNull(),
'password_reset_token' => $this->string()->unique(),
'email' => $this->string()->notNull()->unique(),
'status' => $this->smallInteger()->notNull()->defaultValue(10),
'created_at' => $this->integer()->notNull(),
'updated_at' => $this->integer()->notNull(),
], $tableOptions);
}
public function down()
{
$this->dropTable('{{%user}}');
}
}
执行:/Applications/MAMP/bin/php/php7.1.0/bin/php /Applications/MAMP/htdocs/Tool_fromLoong_server/yii migrate
就自动在我们链接的数据库中创建这样的表啦~再去看下数据库管理工具,发现创建了两张表,一个是用来管理近期操作的migrate,记录操作的migrate的日期和文件。一个是user.
来看下创建一个新的的操作。
1.创建文件,用于执行migrate:
使用php yii migrate/create 类名形式创建,下面是在我的Mac上的例子:
/Applications/MAMP/bin/php/php7.1.0/bin/php /Applications/MAMP/htdocs/advanced/yii migrate/create test_add_new_table
询问是否创建,输入yes或y后。
这时候就会在consle/migrations下创建一个m年月日_****_类名.php文件。
2.编辑文件内容:
根据你所需要的填写PHP文件。
(1)查看新创键的文件:
<?php
use yii\db\Migration;
class m170722_073057_test_add_new_table extends Migration
{
public function safeUp()
{
}
public function safeDown()
{
echo "m170722_073057_test_add_new_table cannot be reverted.\n";
return false;
}
/*
// Use up()/down() to run migration code without a transaction.
public function up()
{
}
public function down()
{
echo "m170722_073057_test_add_new_table cannot be reverted.\n";
return false;
}
*/
}
(2)分析书写你所需的代码:
添加字段写法:
$this->addColumn( 'user', 'test_id','INT(10) NOT NULL COMMENT "测试" AFTER "user_id"');
(3)继续执行最开始执行的安装。/Applications/MAMP/bin/php/php7.1.0/bin/php /Applications/MAMP/htdocs/Tool_fromLoong_server/yii migrate
这个时候提示你的是你没安装过的多有可以被操作的文件,同样根据提示和需求输入yes或no