I'm using psql in my Laravel App. I'm trying to create my user, and I keep getting this error

唯一违规:7错误:重复键值违反唯一约束"USERS_pkey"


Here what I did to store my user

$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();

Here is how I created my users table

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")

);

我做了我想做的事吗?

当我用MySQL勾住我的应用程序时,我现在所拥有的一切都是有用的.

任何提示/建议对我都很重要.


Screenshot

enter image description here

推荐答案

Postgres handles auto incrementing a little differently than MySQL does. In Postgres, when you create the serial field, you are also creating a sequence field that is keeping track of the id to use. This sequence field is going to start out with a value of 1.

When you insert a new record into the table, if you don't specify the id field, it will use the value of the sequence, and then increment the sequence. However, if you do specify the id field, then the sequence is not used, and it is not updated, either.

我假设当您迁移到postgres时,您已经 seeder 或导入了一些现有用户以及他们的现有ID.当您使用其ID创建这些用户记录时,序列没有使用,因此从未更新过.

So, if, for example, you imported 10 users, you have users with ids 1-10, but your sequence is still at 1. When you attempt to create a new user without specifying the id, it pulls the value from the sequence (1), and you get a unique violation because you already have a user with id 1.

要解决此问题,需要将users_id_seq序列值设置为现有用户的最大值(id).有关重置序列的更多信息,您可以阅读this question/answer,但也可以try (未测试):

SELECT setval(pg_get_serial_sequence('users', 'id'), coalesce(max(id)+1, 1), false) FROM users;

仅供参考,这在MySQL中不是问题,因为当手动将值插入自动递增字段时,MySQL会自动将自动递增序列更新为最大列值.

Laravel相关问答推荐

Laravel使用PostgreSQL显示";`try 读取null`上的属性,而不是SQL错误消息

未将Laravel Blade属性传递给组件或类

Livewire 3软件包开发

如何在Vite和Rollup中完全禁用分块?

Npm run dev 卡在 APP_URL

Laravel:BelongstoMany 关系实现

Laravel 在维护模式下显示自定义消息

将 Laravel 升级到 4.2 后,Artisan::call('migrate') 不起作用

如何在 laravel 中安装 PHPExcel 库?

Laravel 中的合同和 PHP 中的接口有什么区别?

在 Laravel 4 迁移中创建 MYSQL 过程

为什么 BroadCastEvent 在 Laravel 中排队?如何阻止它?

Laravel 5.3 通知 - 仅使用Electron邮件地址通知

assets资源不引用公用文件夹(Laravel)

在 laravel 中安装 vue 3.0

Laravel 用户能力

Eloquent - 带有字符串值而不是列标题的连接子句

如何在 Laravel 测试中禁用选定的中间件

Laravel 5 new auth:获取当前用户以及如何实现角色?

在 Laravel 中翻译特定语言