1.創建建表文件
php artisan make:migration create_comments_table
打開database/migrations/xxx_create_comments_table.php:
public function up() { Schema::create('comments',function(Blueprint $table){ $table->engine = 'InnoDB'; $table->increments('id'); $table->integer('article_id'); $table->integer('user_id'); $table->string('content'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('comments'); }
2.生成表
php artisan migrate
3.創建填充表數據的文件
php artisan make:seed ReplyTableSeeder
1).打開:database/seeds/CommentsTableSeeder.php
use Illuminate\Database\Seeder; class CommentsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { factory(\App\Models\Comment::class)->times(30)->create(); // 表示創建30條數據。factory方法對應第三步 } }
2).打開database\seeds\DatabaseSeeder.php
use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $this->call(CommentsTableSeeder::class); // 會調用CommentsTableSeeder的run方法 } }
3).打開database\factories\ModelFactory.php
$factory->define(App\Models\Comment::class, function (Faker\Generator $faker) { $user = DB::table('users')->select('id')->orderBy(DB::raw('RAND()'))->first(); if(empty($user)) { $user->id = 0; } $article = DB::table('articles')->select('id')->orderBy(DB::raw('RAND()'))->first(); if(empty($article)) { $article->id = 0; } return [ 'user_id'=>$user->id, // user表隨機查詢 'article_id'=>$article->id, // 從article表u隨機查詢 'content' => '內容:'.$faker->text, // faker用法自尋,或轉到vendor\fzaninotto\faker\src\Faker\Generator.php,看文件開頭的注釋 ]; });
4).如何讓faker填充中文
打開app\Providers\AppServiceProvider.php:
public function boot() { \Carbon\Carbon::setLocale('zh'); // 針對時間包,轉化后為中文的時間 //生成中文數據 $this->app->singleton(FakerGenerator::class, function() { return FakerFactory::create('zh_CN'); }); }
注:設置后faker屬性仍是英文,是因為包里面就沒有中文數據
4.生成數據
php artisan db:seed
5.假如要新增表,那么在建好建表的文件后,執行php artisan migrate,會提示xxx表已經存在,需要先回滾
php artisan migrate:rollback // 會調用建表文件中的down方法,把數據庫結構恢復到最初狀態