Laravel 5.2 eloquent 在相同的 id 上保存自动增量 pgsql 异常
Laravel 5.2 eloquent save auto increment pgsql exception on same id
我是 laravel 5.2 和 postgres pgsql 的新手。
我有一个名为 logs
的 table
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(但不是空值)。
如果我先保存 Log
,那么它的 id 肯定会是 1,下一个会是 2。
假设我只添加了一条 Eloquent save()
和 id=1
的记录
但问题来了,如果我以某种方式(手动插入查询,或使用 csv 文件)添加 ID 为 2,3,5,8
e.t.c 的新记录。在 table。但是在 save
上以编程方式,
Eloquent 仍然设置 id = 2
第二个 Log
record/entity.
我现在是这样存的
$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 天。提前致谢。
第一列自动递增,如果你需要再添加一个列插入值,像这样取该列的最大值加+1然后保存
Ex:column name log_id 然后在您的存储函数中取最大值 log_id 并添加 +1
$current_id = DB::table('logs')->max('log_id');
'log_id' => $current_id + 1,
或者将您的 id 列更改为 integer 并取最大值添加 +1
我是 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(但不是空值)。
如果我先保存 Log
,那么它的 id 肯定会是 1,下一个会是 2。
假设我只添加了一条 Eloquent save()
和 id=1
但问题来了,如果我以某种方式(手动插入查询,或使用 csv 文件)添加 ID 为 2,3,5,8
e.t.c 的新记录。在 table。但是在 save
上以编程方式,
Eloquent 仍然设置 id = 2
第二个 Log
record/entity.
我现在是这样存的
$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 天。提前致谢。
第一列自动递增,如果你需要再添加一个列插入值,像这样取该列的最大值加+1然后保存
Ex:column name log_id 然后在您的存储函数中取最大值 log_id 并添加 +1
$current_id = DB::table('logs')->max('log_id');
'log_id' => $current_id + 1,
或者将您的 id 列更改为 integer 并取最大值添加 +1