Laravel使用imgrate创建数据表与Seed创建文件

01.创建数据表文件

php artisan make:migration create_user_table --create=user

02.创建字段

public function up()
    {
      Schema::dropIfExists('user');
      Schema::create('user', function (Blueprint $table) {
          $table->Increments('user_id');
          $table->string('username',50);
          $table->string('password',255);
      });
    }

03.查看migrate状态

php artisan migrate:status

04.运行migrate创建

php artisan migrate

05.使用Seed插入数值

A.创建Seed文件
php artisan make:seeder UserTableSeeder

B.编写Seed文件

use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

class UserTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
      DB::table('user')->insert([
            'username' => Str::random(10),
            'password' => bcrypt('123456'),
        ]);
    }
}

C.在DatabaseSeeder中添加刚刚创建的Seed文件,方便以后添加更多的Seed同时插入

public function run()
{
    $this->call([
        UserTableSeeder::class,
        PostsTableSeeder::class,
        CommentsTableSeeder::class,
    ]);
}

D.运行Seed文件
首先需要运行dump-autoload文件
composer dump-autoload
然后运行Seed文件

php artisan db:seed        // 默认运行DatabaseSeeder,包含里面的seed文件

php artisan db:seed --class=UsersTableSeeder    // 指定莫个seed文件
posted @ 2019-08-13 15:23  cicarius  阅读(556)  评论(0编辑  收藏  举报