学习八:修改数据库配置、migration数据表迁移
程序员文章站
2024-03-09 11:47:35
...
数据库配置:
在config.php下面的database.php中,默认是使用mysql数据库
'default' => env('DB_CONNECTION', 'mysql'),
不是在这里修改配置,在.evn文件里配置
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel54
DB_USERNAME=root
DB_PASSWORD=root
因为安全起见,laravel不用再.evn提交暴露给外界
在.gitignore文件中已经设置里不把.evn提交暴露
/node_modules
/public/hot
/public/storage
/storage/*.key
/vendor
/.idea
/.vagrant
Homestead.json
Homestead.yaml
npm-debug.log
yarn-error.log
.env
migration数据表迁移:
1、生成迁移
使用 Artisan 命令 make:migration
来创建一个新的迁移:
php artisan make:migration create_users_table
新的迁移位于 database/migrations
目录下,每个迁移文件名都包含时间戳从而允许 Laravel 判断其顺序。
2、修改创建的表
迁移类包含了两个方法:up
和 down
。up
方法用于新增表,列或者索引到数据库,而 down
方法就是 up
方法的反操作,和up
里的操作相反
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTestTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('test', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamps();//生成updated_at 和created_at 两个字段,更新插入时,自动更新插入时间
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//回滚
Schema::dropIfExists('test');
}
}
3、运行迁移
要运行应用中所有未执行的迁移,可以使用 Artisan 命令提供的 migrate
方法:
php artisan migrate
出现错误:
字段长度大于最大长度
修改:
再次执行php artisan migrate即可