4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravel: DB: マイグレーションとシーダー

Last updated at Posted at 2020-02-11

#####・前提
Laravel5.5 インストール

####・DBテーブルを生成 -> items

DBマイグレーションファイルの作成
$ php artisan make:migration create_items_table
マイグレーションファイルの編集
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 255);
            $table->string('content', 255);
            $table->unsignedInteger('price');
            $table->unsignedInteger('quantity');
            $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
            $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
            $table->softDeletes();
        });
マイグレーションの実行
$ php artisan migrate
マイグレーションを1つ取り消す
$ php artisan migrate:rollback --step=1

####・Modelの生成

$ php artisan make:model Item
app\Item.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Item extends Model
        //指定するテーブル名を追加
        protected $table = 'items';
}

####・Seeder でデータ挿入

Seederファイルの生成
$ php artisan make:seeder ItemTableSeeder
database/seeds/ItemTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Item;

class ItemTableSeeder extends Seeder
    public function run()
    {
        // 商品データを追加
        $item = Item::create([
            'name'     => 'Core i7 9700K BOX',
            'content'    => '8C 8T 3.6GHz LGA1151',
            'price' => 43464,
            'quantity' => 10,
        ]);
        $item = Item::create([
            'name'     => 'Core i5 9600 BOX',
            'content'    => '6C 6T 3.1GHz LGA1151',
            'price' => 26723,
            'quantity' => 15,
        ]);
        $item = Item::create([
            'name'     => 'Core i3 9100 BOX',
            'content'    => '4C 4T 3.6GHz LGA1151',
            'price' => 15787,
            'quantity' => 14,
        ]);
    }
}
$#全シーダーの実行
$ php artisan db:seed
$#特定のシーダーファイル実行
$ php artisan db:seed --class=ItemTableSeeder
シーダーのやり直し(マイグレーションのやり直し)
$ php artisan migrate:rollback --step=1

お疲れさまでした。
DBにデータが格納されたか確認してください。

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?