laravel添加假数据

1、database/migrations建数据表news ,文件名为2017_09_09_000000_create_news_table.php

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNewsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create(‘news’, function (Blueprint $table) {
$table->increments(‘id’)->comment(‘新闻ID’)->unique();
$table->string(‘title’)->comment(‘标题’)->nullable()->index();
$table->string(‘news_category_id’,100)->comment(‘分类’)->nullable()->index();
$table->string(‘image’)->comment(‘缩略图’)->nullable()->index();
$table->string(‘tag’)->comment(‘TAG’)->nullable()->index();
$table->text(‘content’)->comment(‘内容’)->nullable();
$table->integer(‘read_count’)->comment(‘阅读次数’)->nullable()->index();
$table->tinyInteger(‘status’)->default(0)->comment(‘发布:0是,1否’)->nullable()->index();
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
publicfunction down()
{
Schema::dropIfExists(‘news’);
}
}

2、Model里建News.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class News extends BaseModel
{
protected  $fillable= [
‘id’, ‘title’, ‘news_category_id’,’image’,’tag’,’content’, ‘read_count’,’status’
];
}

3、调用模型工厂的文件database/seeds目录下建立文件名:NewsTableSeeder.php

<?php
use Illuminate\Database\Seeder;
class NewsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table(‘news’)->truncate();
factory(App\Models\News::class,20)->create();
}
}

4、模型工厂:database/factories

$factory->define(App\Models\News::class, function (Faker\Generator $faker) {
$NewsCategory= App\Models\NewsCategory::orderBy(\DB::raw(‘RAND()’))->first();
return [
‘title’=>$faker->name,
‘news_category_id’=>$NewsCategory->id,
‘image’=>$faker->image,
‘tag’=>0,
‘content’=>$faker->text,
‘read_count’=>$faker->numberBetween(10,20),
‘status’=>1
];
});
5、生成假数据的操作命令:
composer  dump-autoload
php artisan db:seed  导入所有数据
php artisan db:seed –class=NewsTableSeeder

664 total views, 2 views today

Revisions

There are no revisions for this post.

No comments yet.

发表评论