創(chuàng)建遷移文件
命令php artisan make:migration create_table_admin
格式最好是create_table_表名,執(zhí)行命令完畢,會(huì)產(chǎn)生一個(gè)以時(shí)間開頭的然后后部分自定義的文件,文件中有個(gè)up和down方法,
up用于新增表
down用于刪除表,與up相反
遷移結(jié)構(gòu)
Schema::create('admin',function(Blueprint $table){ $table -> increments('id'); $table -> string('account',50)->default('')->comment('賬號(hào)'); $table -> string('password',250)->default('')->comment('密碼'); $table -> string('nickname',5)->default('')->comment('昵稱'); $table -> timestamps(); });
Schema::create('這里填寫你的表名',function(Blueprint $table){ $table -> increments('id'); //這里是主鍵自增ID,完全自定義,詳情看laravel學(xué)院的文檔 $table -> string('自定義字段名,如 account',50)->default('')->comment('賬號(hào)');//自定義 $table -> string('password',250)->default('')->comment('密碼');//自定義 $table -> string('nickname',5)->default('')->comment('昵稱');//自定義 $table -> timestamps();//會(huì)產(chǎn)生兩個(gè)字段(更新時(shí)間和創(chuàng)建時(shí)間) });
寫好要?jiǎng)?chuàng)建的字段,開始遷移 執(zhí)行以下命令
php artisan migrate
會(huì)提示Migration table created successfully.
說(shuō)明命令遷移成功.到這里遷移完畢
數(shù)據(jù)填充
這里我使用的是模型工廠方式來(lái)填充數(shù)據(jù)
執(zhí)行命令,創(chuàng)建Model
php artisan make:model Model/Admin/Admin
這里注意 命名空間 App\Model\Admin\Admin
創(chuàng)建完畢后,執(zhí)行命令創(chuàng)建填充器
php artisan make:seeder AdminTableSeeder
`
use Illuminate\Database\Seeder;
class AdminTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//factory函數(shù)是插入到數(shù)據(jù)庫(kù),命名空間一定使用你要?jiǎng)?chuàng)建那個(gè)表的模型所在的命名空間
factory('App\Model\Admin\Admin')->create();//
}
}
在ModelFactory.php文件中
$factory->define(App\Model\Admin\Admin::class,function(Faker\Generator $fake){
return [
'account' => 'admin',
'password' => Crypt::encrypt(123456),
'nickname' => '超級(jí)管理員'
];
});$factory->define(創(chuàng)建表的模型所在的命名空間的類,function(Faker\Generator $fake){ return [ 'account' => 'admin',//可以隨機(jī)如 $fake->name; 'password' => Crypt::encrypt(123456), 'nickname' => '超級(jí)管理員' ]; });
以上代碼完畢 可以創(chuàng)建個(gè)測(cè)試方法測(cè)試一下是否能產(chǎn)生數(shù)據(jù),
$res = factory(\App\Model\Admin\Admin::class)->make(); dd($res);
在測(cè)試方法中加上 make是只產(chǎn)生
如果成功 那么執(zhí)行命令