Yii Framework 2.0主键的重复键值

时间:2017-04-04 07:33:31

标签: php postgresql yii2

我不明白它是如何显示主键的重复值错误,即使id是自动增量和主键。请参阅下面的错误。

Integrity constraint violation – yii\db\IntegrityException

SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "user_pkey"
DETAIL: Key (id)=(2) already exists.

1 个答案:

答案 0 :(得分:2)

这意味着smth插入了一行而没有使用序列或更新的id到值2

示例:

t=# create table so47(id serial primary key,v text);
CREATE TABLE
t=# insert into so47(v) select 'some';
INSERT 0 1
t=# insert into so47(id,v) select 2, 'more';
INSERT 0 1
t=# insert into so47(v) select 'some more';
ERROR:  duplicate key value violates unique constraint "so47_pkey"
DETAIL:  Key (id)=(2) already exists.

回答评论中的问题: postgres使用序列获取autoincrement列的下一个值。要检查下一个值,请运行(在我的示例中):

t=# select * from so47_id_seq ;
 sequence_name | last_value | start_value | increment_by |      max_value      | min_value | cache_value | log_cnt | is_cycled | is_called
---------------+------------+-------------+--------------+---------------------+-----------+-------------+---------+-----------+-----------
 so47_id_seq   |          2 |           1 |            1 | 9223372036854775807 |         1 |           1 |      31 | f         | t
(1 row)

要重置nextval,您必须:

t=# alter sequence so47_id_seq restart with 3;
ALTER SEQUENCE
t=# insert into so47(v) select 'some more';
INSERT 0 1

然后它将从不存在的值恢复序列。

在您的情况下,您需要:

select max(id)+1 from "user"

获取值然后:

alter sequence user_id_seq restart with SELECTED_VALUE;