1:置迁移数据表,创建生成模型和迁移文件:
php artisan make:model Article -m
2:接着,在框架中的database/migrations文件夹中找到刚创建的用户表Article
3:打开插入代码:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateArticlesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->string('name','100')->comment('文章标题');
$table->text('content')->comment('文章内容');
$table->string('author')->comment('文章作者');
$table->timestamps();
});
}
/\*\*
\* Reverse the migrations.
\*
\* @return void
\*/
public function down()
{
Schema::dropIfExists('articles');
}
}
4:然后此时执行迁移文件:
php artisan migrate
5:查库看表:
6:最后,我们开始使用Faker填充数据,创建用户的填充文件
php artisan make:seeder ArticleSeeder
7:
此时,我们需要在articles模型层中使用 protected $guarded = [];不然,会无法填充数据
<?php
namespace App\models;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
//
protected $guarded = [];
}
8:接着,我们生成一个数据工厂
php artisan make:factory ArticleFactory -m Models/Article
9:在ArticleFactory .php文件中修改填充文件的数据
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\models\Article;
use Faker\Generator as Faker;
$factory->define(Article::class, function (Faker $faker) {
return [
// 'password' => bcrypt('admin'),
'name' => $this->faker->name,
'content'=>$this->faker->name,
'author' => $this->faker->name,
//password_hash('admin666')
// 'email' => $this->faker->unique()->safeEmail,
// 'phone' => $this->faker->unique()->phoneNumber,
];
});
10:在ArticleSeeder.php文件中:
<?php
use Illuminate\Database\Seeder;
use App\models\Article;
class ArticleSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//重置表数据
Article::truncate();
//生成100条数据
factory(Article::class,100)->create();
//修改id=1用户
Article::where('id', 1)->update(['name' => 'admin']);
}
}
11最后在DatabaseSeeder.php中修改总调用
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
$this->call([
ArticleSeeder::class
]);
}
}
12,终端执行命令
php artisan db:seed
13:查库看表数据:
14,数据填充为中文,修改config\app.php
'faker_locale' => 'zh_CN',
手机扫一扫
移动阅读更方便
你可能感兴趣的文章