LaravelでDBを扱うためにテーブル作成とモデルファイルの作成方法を紹介します。
マイグレーションファイルの作成
下記コマンドでマイグレーションファイルを作成します。
php artisan make:migration create_shops_table --create=shops
create_shops_table部分はマイグレーションのファイル名になりますので任意に書き換えてください。
--create=の後のshopsの部分はテーブル名になりますので任意に書き換えてください。
Laravelではテーブル名は複数形でモデル名称は単数形というのが標準の命名規則になります。
この記事では
・テーブル名
shops
・モデル名
Shop
という名称で進めます。
するとプロジェクトルート/database/migrationsにマイグレーションファイルが生成されます。
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateShopsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('shops', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('shops');
}
}
これを下記のように変更します。
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateShopsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('shops', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->nullable()->comment('店舗名');
$table->string('sub_name')->nullable()->comment('支店名');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('shops');
}
}
マイグレーションファイルを編集したら下記のコマンドでマイグレーションを実行します。
php artisan migrate
こうするとDBにshopsテーブルが作成されます。
モデルファイルの作成
マイグレーションを実行したら下記コマンドでモデルファイルを作成します。
php artisan make:model Shop
するとプロジェクトルート/appに下記のようなShop.phpというファイルが作成されます。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Shop extends Model
{
//
}