You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.5 如何基于自增id自动生成negative_id列?

嘿,我来帮你搞定这个需求!要实现negative_id自动同步为id的负值(比如id=1时negative_id=-1),其实有几种贴合Laravel生态的方案,我给你一步步拆解:

第一步:先通过迁移添加negative_id字段

首先生成迁移文件来新增字段,替换掉your_table_name为你的实际表名:

php artisan make:migration add_negative_id_to_your_table_name_table --table=your_table_name

打开生成的迁移文件,编写字段定义:

public function up()
{
    Schema::table('your_table_name', function (Blueprint $table) {
        // 因为id是唯一正整数,所以negative_id也可以设为唯一负整数
        $table->integer('negative_id')->unique();
    });

    // 如果表已有历史数据,批量填充negative_id
    DB::table('your_table_name')->update([
        'negative_id' => DB::raw('id * -1')
    ]);
}

public function down()
{
    Schema::table('your_table_name', function (Blueprint $table) {
        $table->dropColumn('negative_id');
    });
}

运行迁移生效:

php artisan migrate
方案一:用Laravel模型事件自动同步(最推荐)

因为自增id是数据库生成的,只有在数据插入后才能拿到真实的id值,所以我们可以用created事件来填充negative_id。

打开对应的数据模型(比如YourModel.php),在boot方法里添加事件逻辑:

protected static function boot()
{
    parent::boot();

    static::created(function ($model) {
        // 计算负值并静默更新(避免触发额外事件循环)
        $model->updateQuietly([
            'negative_id' => $model->id * -1
        ]);
    });
}

如果你的业务逻辑比较复杂,也可以把事件抽离到模型观察者里,保持模型干净:

  1. 生成观察者:
php artisan make:observer YourModelObserver --model=YourModel
  1. 在观察者的created方法里写逻辑:
public function created(YourModel $model)
{
    $model->updateQuietly(['negative_id' => $model->id * -1]);
}
  1. 在AppServiceProvider里注册观察者:
use App\Models\YourModel;
use App\Observers\YourModelObserver;

public function boot()
{
    YourModel::observe(YourModelObserver::class);
}
方案二:用数据库触发器(不依赖Laravel逻辑)

如果希望不管通过什么方式插入数据(比如直接数据库操作、第三方工具)都能自动同步negative_id,可以用数据库触发器。

生成专门的迁移来创建触发器:

php artisan make:migration create_negative_id_trigger_for_your_table

在迁移文件里编写触发器逻辑(以MySQL为例):

public function up()
{
    DB::unprepared('
        CREATE TRIGGER set_negative_id AFTER INSERT ON your_table_name
        FOR EACH ROW
        BEGIN
            UPDATE your_table_name SET negative_id = NEW.id * -1 WHERE id = NEW.id;
        END
    ');
}

public function down()
{
    DB::unprepared('DROP TRIGGER IF EXISTS set_negative_id');
}

运行迁移即可生效。

额外小贴士
  • 为了防止negative_id被手动修改,可以在模型里把它加入$guarded数组,禁止批量赋值修改:
protected $guarded = ['negative_id'];

内容的提问来源于stack exchange,提问作者Wonka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:53:37