数据库迁移
一、在项目根目录执行
php artisan make:migration create_test_table
在database/migrations目录中生成迁移文件时间_create_test_table
(表名为test)
//database/migrations/时间_create_test_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTestTable extends Migration
{
/**
* Run the migrations.
*
* @return void//创建数据表
*/
public function up()
{
Schema::create('test', function (Blueprint $table) {
//每一个列的定义代码
$table->increments('id')->comment("主键id,无符号递增");
$table->string('name',100)->comment("用户名");
$table->string('password',100)->comment("密码");
$table->tinyInteger('status')->default(1)->comment("状态值");//默认值为一
// ->nullable()//允许为null
// ->nullnone()//不允许为null
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void//删除数据表
*/
public function down()
{
Schema::dropIfExists('test');//如果存在则删除该数据表
}
}
根据自己的需求对里面的两个方法进行完善,参考官方文档
二、第一次执行数据库库迁移时,要首先执行php artisan migrate:install
进行一个初始化。
数据库中会自动创建一个migrations表,用来记录迁移。
然后执行php artisan migrate
进行迁移。
执行成功之后,数据库中会创建相应的表。
数据回滚执行php artisan migrate:rollback
可以删除刚刚创建的数据表
填充器
一、在根目录执行php artisan make:seeder TestTableSeeder
在database/seeders目录中生成填充器文件TestTableSeeder.php
(表名为test)
二、修改内容,推荐使用DB添加,而不是使用模型。
//database/seeders/TestTableSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class TestTableSeeder extends Seeder
{//填充器
/**
* Run the database seeds.//运行数据库的种子
*
* @return void
*/
public function run()//这里建议使用DB,不用创建模型
{
//定义数组
$data = [
[
'name' => '小白',
'password' => bcrypt(1234)
],[
'name' => '小黑',
'password' => bcrypt(1234)
],[
'name' => '小绿',
'password' => bcrypt(1234)
],
];
//写入数据
DB::table('test')->insert($data);
}
}
三、在姓名根目录执行php artisan db:seed --class=TestTableSeeder
就完成填充了。
注:在分表的时候可以用这个东西。