Laravel 從零開(kāi)始快速創(chuàng)建數(shù)據(jù)庫(kù)測(cè)試數(shù)據(jù)

在命令行從進(jìn)入到 laravel 文件目錄

創(chuàng)建注入文件

在命令行執(zhí)行

php artisan make:migration post

php artisan make:migration post
php artisan make:migration post

書(shū)寫(xiě)數(shù)據(jù)庫(kù)注入代碼

database/migtations 目錄下找到 201x_xx_xx_xxxxxx_post.php 文件

Paste_Image.png

打開(kāi)后寫(xiě)好注入代碼:

<?php

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

class Post extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('text');
        $table->timestamps();
    });
    }

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

運(yùn)行遷移

命令行執(zhí)行

php artisan migrate

Paste_Image.png

執(zhí)行后在數(shù)據(jù)庫(kù)查看結(jié)果

database
database

編寫(xiě)數(shù)據(jù)填充

命令行執(zhí)行

php artisan make:seeder postSeeder

Paste_Image.png

執(zhí)行后在 database/seeds 目錄下找到 postSeeder.php

Paste_Image.png

對(duì)照數(shù)據(jù)庫(kù)表結(jié)構(gòu)添加代碼:

<?php

use Illuminate\Database\Seeder;

class postSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //
        $data = [];
        // 循環(huán)
        for ($i = 0; $i < 20; $i++){
            $tmp = [];
            $tmp['title'] = 'Title-' . str_random(6) .'-'. $i;
            $tmp['text'] = 'Content-' . str_random(100) .'-'. $i;
            $tmp['created_at'] = date('Y-m-d H:i:s');
            $tmp['updated_at'] = date('Y-m-d H:i:s');

            $data[] = $tmp;
        }
        // 插入
        DB::table('posts')->insert($data);
    }
}

填充

找到和 postSeederphp 同目錄下的 DatabaseSeeder.php
在 run 函數(shù)下添加我們的 seeder 類

Paste_Image.png
 public function run()
    {
        Model::unguard();

        // $this->call(UserTableSeeder::class);
        // 添加我們的 postSeeder 類
         $this->call(postSeeder::class);

        Model::reguard();
    }

命令行執(zhí)行

php artisan migrate:refresh --seed

php artisan migrate:refresh --seed
php artisan migrate:refresh --seed

在數(shù)據(jù)庫(kù)中查看

Seeded: postSeeder
Seeded: postSeeder

大功告成!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容