Laravel為了數據能夠更方便的填入資料庫,專門定義了一個填充類,可以為你的資料庫填充測試數據,所有的填充類別都放在database/seeds 目錄下,本文就帶大家一起來看看。
一、寫Seeders 並填入資料
利用 Artisan 指令 make:seeder 產生 Seeder
php artisan make:seeder UserSeeder
產生UserSeeder 類別
<?php namespace Database\Seeders; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class UserSeeder extends Seeder { public function run() { } }
DB::table('users')->insert( [ ['name' => '321250887','email' => '321250887@qq.com','password' => bcrypt('321250887')], ['name' => '321250888','email' => '321250888@qq.com','password' => bcrypt('321250888')], ['name' => '321250889','email' => '321250889@qq.com','password' => bcrypt('321250889')], ['name' => '3212508810','email' => '3212508810@qq.com','password' => bcrypt('3212508810')], ['name' => '3212508811','email' => '3212508811@qq.com','password' => bcrypt('3212508811')], ['name' => '3212508812','email' => '3212508812@qq.com','password' => bcrypt('3212508812')], ['name' => '3212508813','email' => '3212508813@qq.com','password' => bcrypt('3212508813')], ['name' => '3212508814','email' => '3212508814@qq.com','password' => bcrypt('3212508814')], ]); //相应的类已经在上方导入
php artisan db:seed --class=UserSeeder
二、使用預設的DatabaseSeeder 類別並填入資料
<?php namespace Database\Seeders; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class DatabaseSeeder extends Seeder { public function run() { DB::table('users')->insert([ 'name' => '3212508814', 'password' => bcrypt('3212508814')], ]); } }
public function run() { $this->call([ UserSeeder::class, CategorySeeder::class, ]); }
php artisan db:seed
影片教學#
以上是laravel框架中的資料填充的詳細內容。更多資訊請關注PHP中文網其他相關文章!