Laravel 5 数据库迁移文件示例
php artisan make:migration create_stocks_table
在项目根目录执行上面的命令后,会在database/migrations目录下生成2016_06_03_100344_create_stocks_table.php(名称与时间有关)文件,修改这个文件就可以了,修改后如下
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use Illuminate\Support\Facades\Schema; class CreateStocksTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('stocks',function(Blueprint $table) { $table->increments('id'); $table->string('sku'); $table->string('name'); $table->string('warehouse'); $table->string('platform'); $table->integer('quantity'); $table->integer('valid'); $table->integer('update_time'); $table->index(array('sku')); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('stocks'); } }
文件内容很容易理解,具体有那些创建数据表字段的方法可以参考文件Illuminate\Database\Schema\Blueprint.php,很容易理解
然后执行如下命令即可,此命令实际是调用刚刚的up方法,
php artisan migrate
调用down方法执行如下命令
php artisan migrate:rollback
数据表已经创建好了,接下来填充测试数据
php artisan make:seeder StocksTableSeeder
执行上面的命令后,会在database/seeds下生成StocksTableSeeder.php文件,我们修改这个文件的run方法,添加填充数据命令,修改后的文件如下
<?php use Illuminate\Database\Seeder; use Illuminate\Database\Eloquent\Model; class StocksTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('stocks')->insert([ 'sku' => str_random(5), 'name' => str_random(10), 'warehouse' => str_random(6), 'platform' => str_random(3), 'quantity' => rand(10,100), 'valid' => rand(10,100), 'update_time' => rand(strtotime("-10 days"),time()) ]); } }
然后修改同目录下的DatabaseSeeder.php,添加上面类的调用
<?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $this->call(StocksTableSeeder::class); } }
最后在命令行多次执行,批量填充测试数据的方法参考官方手册
php artisan db:seed
查看数据库如下