【问题标题】:Laravel 5.2 eloquent save auto increment pgsql exception on same idLaravel 5.2 雄辩的在相同的 id 上保存自动增量 pgsql 异常
【发布时间】:2016-07-09 11:54:16
【问题描述】:

我是 laravel 5.2 和 postgres pgsql 的新手。 我有一张名为logs的表

Schema::create('logs', function(Blueprint $table){
                $table->bigIncrements('id');
                $table->text('exception');
                $table->dateTime('created_at');
            });

和相应的模型Log

    class Log extends Model{
        public $incrementing = true;
        public $timestamps = false;
}

据我了解(可能有误)。如果没有给出id,那么 Eloquent 会将最后使用的 id + 1(但不是 null 反对它)。 如果我先保存Log,那么它的 id 肯定是 1,下一个是 2。 假设我只添加了一条 Eloquent save() 和 id=1 的记录

但是问题来了,如果我以某种方式(手动使用插入查询或使用 csv 文件)添加 ID 为 2,3,5,8 等的新记录。在表中。但以编程方式在save 上, Eloquent 仍然将id = 2 设置为第二个Log 记录/实体。

我现在这样保存

$l = new Log();
$l->exception = "some exception";
$l->created_at = Carbon::now()->toDateTimeString();

while(true){
    try{
          $l->save(); //it auto increments the id on each try
          break;
    }catch(\Exception $e){
          continue;
    }
 }

观看循环,上面的解决方案对我有用,它会自动添加带有id = 4 的记录(在上述条件下)。它抛出并捕获 id 2 和 3 的两个异常。

我不喜欢这个解决方案,请给我一些建议,我正在寻找一个没有循环的修复,将近 2 天。提前致谢。

【问题讨论】:

    标签: php postgresql laravel eloquent plpgsql


    【解决方案1】:

    如果您需要再添加一个列插入值,则第一列自动递增,取该列的最大值添加+1,然后保存

    例如:列名 log_id 然后在您的存储函数中取最大值 log_id 并添加 +1

    $current_id = DB::table('logs')->max('log_id');
    
    'log_id' => $current_id + 1,
    

    或者将您的 id 列更改为 integer 并取最大值添加 +1

    【讨论】:

    • 是的,这很好。但这会扼杀串行数据类型的好处。让我们这样看,在一个非常大的数据库(数百万条记录)上,max('log_id') + 1; 或try catch 循环哪个更有效?我认为 max one 可能更好。
    • 是的,避免了这种循环,只需在尝试中保存$l->save();。并抓住你建议的方式。
    猜你喜欢
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    • 2016-04-19
    • 2020-06-10
    • 2016-11-03
    相关资源
    最近更新 更多