kyo*_*kyo 11 php mysql postgresql laravel laravel-5
我在Laravel应用程序中使用psql.我正在尝试创建我的用户,并且我一直收到此错误
唯一违规:7错误:重复键值违反唯一约束"users_pkey"
$user = User::where('account_id','=',$id)->first();
$user->email = $account->email_address;
$user->fb_email = '';
$user->tw_email = '';
$user->fb_access_token = '';
$user->fb_profile_id = '';
$user->fb_page_id = '';
$user->fb_username = '';
$user->save();
Run Code Online (Sandbox Code Playgroud)
CREATE TABLE "users" (
"id" serial NOT NULL ,
"account_id" varchar(255) NOT NULL ,
"email" varchar(255) NOT NULL ,
"fb_email" varchar(255) NOT NULL ,
"tw_email" varchar(255) NOT NULL ,
"created_at" timestamp(0) without time zone,
"updated_at" timestamp(0) without time zone,
"fb_access_token" varchar(255) NOT NULL ,
"fb_profile_id" varchar(255) NOT NULL ,
"fb_page_id" varchar(255) NOT NULL ,
"fb_username" varchar(255) NOT NULL ,
PRIMARY KEY ("id")
);
Run Code Online (Sandbox Code Playgroud)
我做过任何我想做的事not
吗?
我现在所拥有的东西曾经在我用我的应用程序挂钩时工作MySQL
.
任何提示/建议对我来说意义重大.
pat*_*cus 29
Postgres处理自动递增的方式与MySQL略有不同.在Postgres中,当您创建serial
字段时,您还要创建一个序列字段来跟踪要使用的ID.该序列字段将以值1开始.
在表中插入新记录时,如果未指定该id
字段,则将使用序列的值,然后递增序列.但是,如果您指定了该id
字段,则不会使用该序列,也不会更新该序列.
我假设当你转移到Postgres时,你会播种或导入一些现有用户以及他们现有的ID.当您使用其ID创建这些用户记录时,未使用该序列,因此它从未更新过.
因此,例如,如果您导入了10个用户,则您的用户具有ids 1-10,但您的序列仍为1.当您尝试创建新用户而未指定ID时,它会从序列中提取值( 1),你得到一个独特的违规,因为你已经有一个id为1的用户.
要解决此问题,您需要将users_id_seq
序列值设置为现有用户的MAX(id).您可以阅读此问题/答案以获取有关重置序列的更多信息,但您也可以尝试类似(未经测试):
SELECT setval(pg_get_serial_sequence('users', 'id'), coalesce(max(id),1), false) FROM users;
Run Code Online (Sandbox Code Playgroud)
仅供参考,这在MySQL中不是问题,因为当手动将值插入自动递增字段时,MySQL会自动将自动增量序列更新为最大列值.
小智 10
下面的代码提供了一种在 Laravel 中执行此操作的方法,这也是 OP 正在使用的方法。
// Get all the tables from your database
$tables = \DB::select('SELECT table_name FROM information_schema.tables WHERE table_schema = \'public\' ORDER BY table_name;');
// Set the tables in the database you would like to ignore
$ignores = array('admin_setting', 'model_has_permissions', 'model_has_roles', 'password_resets', 'role_has_permissions', 'sessions');
//loop through the tables
foreach ($tables as $table) {
// if the table is not to be ignored then:
if (!in_array($table->table_name, $ignores)) {
//Get the max id from that table and add 1 to it
$seq = \DB::table($table->table_name)->max('id') + 1;
// alter the sequence to now RESTART WITH the new sequence index from above
\DB::select('ALTER SEQUENCE ' . $table->table_name . '_id_seq RESTART WITH ' . $seq);
}
}
Run Code Online (Sandbox Code Playgroud)
注意 - 使用 ALTER SEQUENCE “阻止并发事务”。如果不需要,请考虑使用上面提供的替代解决方案中的 SQL 语句。
归档时间: |
|
查看次数: |
10207 次 |
最近记录: |