概要
この記事に書かれているのと、ほぼ同じようなことを Laravel で行うために、0 から 9 までの値を持つテーブルと、1 から 500 までの値を持つビューを、マイグレーションとシーダーを使って作成したのでメモ。
マイグレーションを使って 0 から 9 までの値を入れるテーブルを作成
$ php artisan make:migration create_digits_table --create=digits
database/migrations/2016_04_15_000000_create_digits_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDigitsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('digits', function (Blueprint $table) {
$table->integer('digit')->unsigned();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('digits');
}
}
シーダーを使って 0 から 9 までの値を挿入
$ artisan make:seeder DigitsTableSeeder
database/seeds/DigitsTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class DigitsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$table = DB::table('digits');
$table->truncate();
foreach (range(0, 9) as $digit)
{
$table->insert([ 'digit' => $digit ]);
}
}
}
マイグレーションを使って 1 から 500 までの値を持つビューを作成
$ php artisan make:migration create_sequence500_view
database/migrations/2016_04_15_000000_create_sequence340_view.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSequence500View extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (DB::table('digits')->count() !== 10)
{
Artisan::call('db:seed', [ '--class' => 'DigitsTableSeeder' ]);
}
DB::statement('
CREATE VIEW
`vw_sequence500`
AS
SELECT
(`d1`.`digit` + (`d2`.`digit` * 10) + (`d3`.`digit` * 100)) AS `number`
FROM
(`digits` AS `d1` JOIN `digits` AS `d2` JOIN `digits` AS `d3`)
ORDER BY
`number`
LIMIT
1, 500
');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::statement('DROP VIEW `vw_sequence500`');
}
}
※ ビューを作る前にシーダーを実行するようにしている。
マイグレーションを実行
$ php artisan migrate