我的 MySQL 数据库中有一个表,其中包含一些现有列。我想使用 Laravel 迁移向其中一列添加评论,以提供有关其用途的更多信息。
我知道我可以在使用 comment() 方法创建迁移时向新列添加注释。但是,我不确定如何向现有列添加评论。
有人可以提供一个示例,说明如何修改 Laravel 迁移中的现有列以添加注释吗?例如,我想向我的
email
表中的 users
列添加注释。
数据库已经存在,我想应用迁移而不重新创建部分数据库,只需更新它。
参见文档:
https://laravel.com/docs/7.x/migrations#modifying-columns
创建迁移文件:
<?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::table('users', function (Blueprint $table) {
$table->string('name', 255)->comment('comment added')->change();
});
}
};
然后
php artisan migrate
将添加评论:
mysql> show full columns from users;
+-------------------+---------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+-------------------+---------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------------+
| id | bigint(20) unsigned | NULL | NO | PRI | NULL | auto_increment | select,insert,update,references | |
| name | varchar(255) | utf8mb4_unicode_ci | NO | | NULL | | select,insert,update,references | comment added |
| email | varchar(255) | utf8mb4_unicode_ci | NO | UNI | NULL | | select,insert,update,references | |
| email_verified_at | timestamp | NULL | YES | | NULL | | select,insert,update,references | |
| password | varchar(255) | utf8mb4_unicode_ci | NO | | NULL | | select,insert,update,references | |
| remember_token | varchar(100) | utf8mb4_unicode_ci | YES | | NULL | | select,insert,update,references | |
| created_at | timestamp | NULL | YES | | NULL | | select,insert,update,references | |
| updated_at | timestamp | NULL | YES | | NULL | | select,insert,update,references | |
+-------------------+---------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------------+
8 rows in set (0.02 sec)
注意:(目前)没有办法“仅添加评论”而不再次表达类型。这不是 Laravel 的限制,而是 SQL 的一般限制。请参阅有关使用一个 SQL 查询添加注释的相关问题(剧透:它仍然需要表达列类型):
首先你需要使用下面的命令安装doctrine/dbal包
composer require doctrine/dbal
然后创建迁移以进行更改
php artisan make:migration add_comment_to_email_column_in_users_table
在创建的迁移文件中进行更改
Schema::table('users', function (Blueprint $table) {
$table->string('email')->unique()->comment('email')->change();
});
然后运行
php artisan migrate
public function up() {
Schema::table('product', function (Blueprint $table) {
$table->string('product_type')
->comment('0 = A Industrial Products, 1 = A Consumer Products')
->change();
});
}