在命令行从进入到 laravel 文件目录
创建注入文件
在命令行执行
php artisan make:migration post

php artisan make:migration post
书写数据库注入代码
在 database/migtations
目录下找到 201x_xx_xx_xxxxxx_post.php
文件
Paste_Image.png
打开后写好注入代码:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Post extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('text');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
Schema::drop('posts');
}
}
运行迁移
命令行执行
php artisan migrate
Paste_Image.png
执行后在数据库查看结果

database
编写数据填充
命令行执行
php artisan make:seeder postSeeder
Paste_Image.png
执行后在 database/seeds
目录下找到 postSeeder.php
Paste_Image.png
对照数据库表结构添加代码:
<?php
use Illuminate\Database\Seeder;
class postSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//
$data = [];
// 循环
for ($i = 0; $i < 20; $i++){
$tmp = [];
$tmp['title'] = 'Title-' . str_random(6) .'-'. $i;
$tmp['text'] = 'Content-' . str_random(100) .'-'. $i;
$tmp['created_at'] = date('Y-m-d H:i:s');
$tmp['updated_at'] = date('Y-m-d H:i:s');
$data[] = $tmp;
}
// 插入
DB::table('posts')->insert($data);
}
}
填充
找到和 postSeederphp
同目录下的 DatabaseSeeder.php
在 run 函数下添加我们的 seeder 类
Paste_Image.png
public function run()
{
Model::unguard();
// $this->call(UserTableSeeder::class);
// 添加我们的 postSeeder 类
$this->call(postSeeder::class);
Model::reguard();
}
命令行执行
php artisan migrate:refresh --seed

php artisan migrate:refresh --seed
在数据库中查看

Seeded: postSeeder
大功告成!