Open3
Laravel テーブル新規作成
Laravelでテーブルを作成する場合はマイグレーションファイルを使用すること!
直接mySqlなどでテーブルを作ると連係が取れなくなったりするかも。
マイグレーションファイルの新規作成。
sail aritisan make:migration マイグレーションファイル名
php artisan make:migratino マイグレーションファイル名
Modelと設定で作成することもできる。
sail artisan make:model Test -m
php artisan make:model Test -m
マイグレーションファイルはdatabase/migrations
の中にある。
Modelと一緒に作成した場合は、app/Models/Test.php
とモデルファイルが出来てる。
マイグレーションファイルは以下のようにupメソッドとdownメソッドが記載されている。
database/migrations/2023_10_29_201325_create_tests_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('tests', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('tests');
}
};
このupメソッドにデータベースにどういったカラムを設定するか記載する。
たとえば、Userというテーブルを作成してユーザー情報のカラムを作成したい場合。
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
//
//$talble ->データの型('カラム名')->カラム修飾子
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
}
};
カラムの設定方法としては上記にコメントで書いたある通り。データ型とカラム修飾子などが必要になる。
例えばnullable()
という修飾子はNullを許容するという意味。unique()
はカラムに重複した値を入れないという意味。
新規テーブルを作成する際はdownメソッドはもともと記載されているが、本来カラムを追加したいなどする場合はdownメソッドにupメソッドと逆のことを記載する!?
上記の例でいえばdownメソッドは、usersが存在した場合は削除するという追加とは逆の意味。
マイグレーションファイルをデータベースに反映させるには以下のコマンド
sail artisan migrate
php artisan migrate