最近开始学习Laravel,此学习笔记仅给自己作知识点归纳整理复习之用。
一、PS进入Laravel目录输入 php artisan make:model Article --migration,创建Migration文件和Model文件。
二、Migration文件修改如下:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArticlesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('articles');
}
}
三、ModelFactory文件修改如下:
<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\Article::class, function (Faker\Generator $faker) {
static $password;
return [
'title' => $faker->sentence,
'content' => $faker->text,
// 'password' => $password ?: $password = bcrypt('secret'),
// 'remember_token' => str_random(10),
];
});
四、DatabaseSeeder文件修改如下:
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// $this->call(UsersTableSeeder::class);
factory(App\Article::class,100)->create();
}
}
五、最后PS输入 php artisan migrate:refresh --seed,创建数据库以及填充数据。
可能出现的问题:
1、SQLSTATE[42000]错误
解决方法:在App\Providers\AppServiceProvider中的boot方法添加 Schema::defaultStringLength(191);并添加引用use Illuminate\Support\Facades\Schema;
2、SQLSTATE[HY000]错误
解决方法:数据库连接错误,进入.env修改数据库连接相关参数。