Laravel数据表迁移与填充

创建模型与填充文件:
例如:创建一个文章数据表

php artisan make:model Article -m

-m 是 --migration 的缩写,告知 Artisan 在创建模型同时创建与之对应的迁移文件
在这里插入图片描述
迁移文件位置 项目根目录\database\migrations

<?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'); //id
      $table->string('title');	//文章标题
      $table->string('outline');//概要
      $table->string('author');//作者
      $table->text('content'); //内容
      $table->text('html');		//html内容
      $table->string('category');	//类别
      $table->string('tag');	//标签
      $table->timestamps();		
    });
  }

  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    Schema::dropIfExists('articles');
  }
}

列类型可查看
执行迁移文件

php artisan migrate

在这里插入图片描述

模型:

<?php

namespace App\Admin;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    //定义模型关联的数据表 文章表
    protected $table = 'articles';
    //定义主键
    protected $primaryKey = 'id';
    //定义禁止操作时间
    public $timestamps = false;
    //定义允许写入的数据字段
    protected $fillable = [
    'id', 
    'title',
    'author',
    'outline', 
    'content',
    'html',
    'category',
    'tag',
    'created_at', 
    'updated_at'];
}

创建填充器,生成随机测试数据

php artisan make:seeder ArticlesTableSeeder

在这里插入图片描述
填充器位置:项目根目录下\database\seeds
使用faker库快速填充数据,
可查看

<?php

use Illuminate\Database\Seeder;
use App\Article;

class ArticlesTableSeeder extends Seeder
{
  /**
   * Run the database seeds.
   *
   * @return void
   */
  public function run()
  {
    // Let's truncate our existing records to start from scratch.
    Article::truncate();

    $faker = \Faker\Factory::create();
    $categoryList = ['前端', '后端', '网络'];
    $tagList = ['JAVA', 'PHP', 'Mysql', 'Javascript', 'Python'];

    // And now, let's create a few articles in our database:
    for ($i = 0; $i < 20; $i++) {
      Article::create([
        'title' => $faker->sentence,
        'outline' => $faker->sentence,
        'author' => '8963',
        'content' => $faker->paragraph,
        'html' => $faker->paragraph,
        'category' => $faker->randomElement($categoryList),
        'tag' => $faker->randomElement($tagList),
      ]);
    }
  }
}

执行数据填充命令,生成数据

php artisan db:seed --class=ArticlesTableSeeder

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值