Laravel 生成假数据步骤

  1. 生成数据模型
    我们为资源推荐模型取名 Link ,使用命令行新建模型,顺便创建数据库迁移:

$ php artisan make:model Models/Link -m
修改数据库迁移文件为以下:

{timestamp}_create_links_table

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateLinksTable extends Migration
{
public function up()
{
Schema::create('links', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->comment('资源的描述')->index();
$table->string('link')->comment('资源的链接')->index();
$table->timestamps();
});
}

public function down()
{
    Schema::dropIfExists('links');
}

}
执行数据库迁移生成表结构:

$ php artisan migrate
基于过去的经验,我们知道还需要定义模型的 $fillable 字段,否则将无法更新数据:

app/Models/Link.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Link extends Model
{
protected $fillable = ['title', 'link'];
}

  1. 生成假数据
    第一步:生成数据工厂
    $ php artisan make:factory LinkFactory
    修改为以下:

database/factories/LinkFactory.php

<?php

use Faker\Generator as Faker;

$factory->define(App\Models\Link::class, function (Faker $faker) {
return [
'title' => $faker->name,
'link' => $faker->url,
];
});
第二步:生成填充类
$ php artisan make:seeder LinksTableSeeder
修改为以下:

database/seeds/LinksTableSeeder.php

<?php

use Illuminate\Database\Seeder;
use App\Models\Link;

class LinksTableSeeder extends Seeder
{
public function run()
{
// 生成数据集合
$links = factory(Link::class)->times(6)->make();

    // 将数据集合转换为数组,并插入到数据库中
    Link::insert($links->toArray());
}

}
第三步:注册 DatabaseSeeder
新增调用:

database/seeds/DatabaseSeeder.php

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call(UsersTableSeeder::class);
$this->call(TopicsTableSeeder::class);
$this->call(ReplysTableSeeder::class);
$this->call(LinksTableSeeder::class);
}
}
第四步:重新生成数据
刷新数据库,然后重新生成数据:

$ php artisan migrate:refresh --seed

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 2

md 美化下更好

6年前 评论

@lovecn 抱歉,我这就是在教程里面复制下来的,记录一下,方便自己回去查看的。

6年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!