数据迁移 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(); 封装。

蔺焕然
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
最佳答案

当然可以,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();
});
1年前 评论
蔺焕然 (楼主) 1年前
讨论数量: 3
蔺焕然

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

1年前 评论

当然可以,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();
});
1年前 评论
蔺焕然 (楼主) 1年前

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