数据迁移 Migration 如何创建自定义字段

当前框架版本

Laravel Framework 9.52.10

问题叙述

这是目前迁移的使用方式

    public function up(): void
    {
        Schema::create('company', function (Blueprint $table) {
            $table->id();
            $table->string('name', 50)->comment('公司名称')->default('');
            $table->tinyText('remark')->nullable()->comment('备注');
            $table->timestamp('created_at')->comment('created time')->useCurrent();
            $table->timestamp('updated_at')->comment('updated time')->useCurrent()->useCurrentOnUpdate();
            $table->timestamp('deleted_at')->nullable()->default(NULL)->comment('delete time');
            $table->comment('公司表');
        });
    }

但是像 created_at updated_at deleted_at 这种字段每个表都存在。
请问能否可以自定义列格式 比如 扩充新 created_at 类型 对原来 $table->timestamp('created_at')->comment('created time')->useCurrent(); 封装。

蔺焕然
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
最佳答案

当然可以,Blueprint 对象是支持 “宏扩展的”,直接在 AppServiceProvider 的 boot 方法里面写就好了。

use Illuminate\Database\Schema\Blueprint;

Blueprint::macro('user', function (string $column = 'user_id', string $comment = '用户') {
    return $this->unsignedBigInteger($column)->comment($comment)->index();
});
6个月前 评论
蔺焕然 (楼主) 6个月前
讨论数量: 3
蔺焕然

尝试重写 Illuminate\Database\Schema\Blueprint 貌似不可行

6个月前 评论

当然可以,Blueprint 对象是支持 “宏扩展的”,直接在 AppServiceProvider 的 boot 方法里面写就好了。

use Illuminate\Database\Schema\Blueprint;

Blueprint::macro('user', function (string $column = 'user_id', string $comment = '用户') {
    return $this->unsignedBigInteger($column)->comment($comment)->index();
});
6个月前 评论
蔺焕然 (楼主) 6个月前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!