実現したいこと
1.DB(データベース)のテーブルに対して、日本語名称のコメントを付与したい。
参考画像:testsテーブルに対して「テストテーブル」のコメントを付与
2.DB(データベース)のカラムに対して、日本語名称のコメントを付与したい。
参考画像:testsテーブルのnameカラムに対して「名称」のコメントを付与
実現方法
1.DB(データベース)のテーブルに対して、日本語名称のコメントを付与
DB::statement("ALTER TABLE `tests` comment 'テストテーブル'");
マイグレーションファイル(新規作成)
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTestsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tests', function (Blueprint $table) {
$table->id();
$table->string('name')->comment('名称');
$table->timestamps();
});
DB::statement("ALTER TABLE `tests` comment 'テストテーブル'");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tests');
}
}
2.DB(データベース)のカラムに対して、日本語名称のコメントを付与
$table->string('name')->comment('名称');
マイグレーションファイル(新規作成)
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTestsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tests', function (Blueprint $table) {
$table->id();
$table->string('name')->comment('名称');
$table->timestamps();
});
DB::statement("ALTER TABLE `tests` comment 'テストテーブル'");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tests');
}
}
補足
1.カラムに対してのコメントは末尾以外に付与しても動作は問題ないか。
$table->string('name')->nullable()->comment('名称');
ではなく
$table->string('name')->comment('名称')->nullable();
だった場合は正常に動作するでしょうか。
結論、動作します。
2.テーブル名にコメントを付与する記述方をマイグレーション記法にしたい場合
Laravel9.14で導入され、実現できるようになったようです。
[9.x] Add ability to add table comments for MySQL and Postgres by andrewbroberg · Pull Request #42401 · laravel/framework
This PR adds the ability to add a comment to a table in MySQL and Postgres
Schema::table('posts', function (Blueprint $table) {
$table->comment(&...
マイグレーション記法
$table->string('name')->comment('コメント');
3.マイグレーション更新ファイルで実行したい場合
マイグレーションファイル作成コマンド
php artisan make:migration add_comment_tests_table --table=tests
マイグレーションファイル(更新)
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddCommentTestsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tests', function (Blueprint $table) {
$table->id();
$table->string('name')->comment('名称')->change();
$table->timestamps();
});
DB::statement("ALTER TABLE `tests` comment 'テストテーブル'");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
$table->string('name')->comment('変更前の値')->change();
DB::statement("ALTER TABLE `tests` comment '変更前の値'");
}
}
downメソッドにあるロールバックされる処理は変更前の値を挿入します。
コメントが元々何も付与されていなかった場合は「空」を指定しましょう。
コメント