Laravel5.6 ORM Eloquent artisan make table and migration ,generate seeder

make model

php artisan make:model Student

ps 如果表名是单数,这里要覆写表名

make migration 模板

php artisan make:migration create_student_table

然后修改模板如下:

public function up()
{   
     Schema::create('student', function (Blueprint $table) {

      $table->increments('id');
      $table->string('name',50)->comment('学生姓名');
      $table->string('tel',15)->comment('学生手机');
      $table->string('email',100)->comment('学生企业邮箱')->nullable();
      $table->integer('school')->comment('毕业学校')->nullable();
      $table->string('age')->comment('年龄');//normal score
      $table->string('mem')->comment('备注');//normal score
      $table->timestamps();

      $table->unique('email');
      }); 
}   

关于$table字段类型及后续操作方法,或许后续会整理,这里先问搜索引擎吧。

数据迁移,生成表

php artisan migrate

使用 artisan 生成 Seeder

php artisan make:seeder StudentSeeder

这一步操作会生成 seeder 样板文件:database/seeds/StudentSeeder.php,然后修改如下:

public function run()
{   
    DB::table('student')->delete();
    for($i=0;$i<100;$i++){
        \App\Student::create([
            'name'=>'student'.$i,
            'tel'=>13911483000+$i,
            'email'=>'student'.$i.'@'.$i.'com',
            'school'=>mt_rand(1,100),
            'age'=>mt_rand(18,32),
            'mem'=>'some memory message!',
       ]); 
    }   
}  

注册StudentSeeder到系统内

修改 database/seeds/DatabaseSeeder.php 中的 run 函数为:

public function run()
{
$this->call(StudentSeeder::class);
}

最后的最后,令人兴奋的魔法来了:

php artisan db:seed

ps:如果这一步没有成功,可能是由于 database 目录没有像 app 目录那样被 composer 注册为 psr-4 自动加载,采用的是 psr-0 classmap 方式,所以我们还需要运行以下命令把 StudentSeeder.php 加入自动加载系统:

composer dump-autoload

然后再执行上面的命令,如果没有其他问题,现在刷新一下数据库看一下结果吧!


以下是赠品:

其实,artisan 可不仅是创建表,生成样本数据这么简单,还能做很多,(懒病又发作了,要混了),如:

修改已创建的数据表字段:

php artisan make:migration add_to_student_table --table=student
php artisan make:migration change_on_student_table --table=student

创建控制器: php artisan make:controller StudentController

创建Eloquent 模型:php artisan make:model Student

还有很多,可使用 php artisan list 一一查看

猜你喜欢

转载自blog.csdn.net/yageeart/article/details/79689093