草庐IT

php - CakePHP:唯一违规:7 错误:重复键值违反唯一约束

coder 2024-04-17 原文

在尝试删除一堆记录然后插入新记录后,我遇到了以下错误:

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

SQL Query:
INSERT INTO routes (agency_id, route_identifier, short_name, long_name, description, route_color, text_color) VALUES (:c0, :c1, :c2, :c3, :c4, :c5, :c6) RETURNING *

这是代码的简化版本:

    $routes = TableRegistry::get('Routes');
    $routes->deleteAll(['agency_id' => $agency->id]);

    # Data to be updated
    $patchData = [
        'stops' => $stopData,
        'static_data_modified' => Time::now()
    ];

    $patchOptions = [
        'associated' => ['Stops.Routes']
    ];

    # If: The stops have already been added to the DB
    # Then: Remove them from the patch data
    if (isset($stopData['_ids'])) {
        unset($patchData['stops']);

        # Change settings for this implementation type
        $patchOptions = [];
        $stopCount = count($stopData['_ids']);
    }

    $agency = $this->Agencies->patchEntity($agency, $patchData, $patchOptions);

    $this->Agencies->save($agency);

似乎出于某种原因,Postgres 认为我正在插入一条具有重复主键的记录。但我无法从我的代码中看出这怎么可能。

这是我在 SQL 日志末尾看到的内容:

DELETE FROM 
  routes 
WHERE 
  agency_id = 51

BEGIN

SELECT 
  1 AS "existing" 
FROM 
  agencies Agencies 
WHERE 
  Agencies.id = 51 
LIMIT 
  1

INSERT INTO routes (
  agency_id, route_identifier, short_name, 
  long_name, description, route_color, 
  text_color
) 
VALUES 
  (
    51, '100001', '1', '', 'Kinnear - Downtown Seattle', 
    '', ''
  ) RETURNING *

ROLLBACK

我为什么会看到这个错误有什么想法吗?

我在 CakePHP v3.1 和 Postgresql 9.4 上

我尝试添加这个但它没有改变任何东西:

$connection = ConnectionManager::get('default');
$results = $connection->execute('SET CONSTRAINT = routes_pkey DEFERRED');

以下是我读过但没有找到解决方案的类似问题:

更新 在 muistooshort 的评论之后,我从路由表中删除了所有记录并重新运行代码并且它工作正常。在那之后我第二次运行它时它也工作正常。所以我认为这支持了 mu 的理论,即数据库中的现有记录有问题(不是我的代码)。我认为现在更好的问题是数据库中到底是什么情况导致了这种情况,我该如何解决?

最佳答案

serial type在 PostgreSQL 中非常简单:它本质上是一个 integer 列,其默认值来自 sequence .但是序列不知道您对表做了什么,因此如果您在没有使用或更新序列的情况下为 serial 指定一个值,事情就会变得困惑。

例如:

create table t (
  id serial not null primary key
);
insert into t (id) values (1);
insert into t (id) values (DEFAULT);

将产生唯一性冲突,因为 1 已明确用于 id,但序列无法知道它已被使用。

演示:http://sqlfiddle.com/#!15/17534/1

大概是在某个时间某处添加了一行 id = 1328 而没有 id 来自序列。或者可能使用 setval 调整了用于 PK 默认值的序列开始返回表中已有的值。

无论如何,最简单的做法是使用 setval 调整顺序以匹配表格的当前内容:

select setval('routes_id_seq', (select max(id) from routes));

该序列应该被称为 routes_id_seq 但如果不是,您可以在 psql 中使用 \d routes 来找出它的内容名字是。

因此,如果我们将前面的示例更新为:

create table t (
  id serial not null primary key
);
insert into t (id) values (1);
select setval('t_id_seq', (select max(id) from t));
insert into t (id) values (DEFAULT);

然后我们将在表中得到 12 而不是 1 和一个错误。

演示:http://sqlfiddle.com/#!15/17534/7

关于php - CakePHP:唯一违规:7 错误:重复键值违反唯一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36461348/

有关php - CakePHP:唯一违规:7 错误:重复键值违反唯一约束的更多相关文章

  1. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  2. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

  3. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  4. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  5. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  6. ruby-on-rails - 错误 : Error installing pg: ERROR: Failed to build gem native extension - 2

    我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby​​'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe

  7. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  8. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

  9. ruby-on-rails - Rails 5 Active Record 记录无效错误 - 2

    我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa

  10. arrays - 这是 Ruby 中 Array.fill 方法的错误吗? - 2

    这个问题在这里已经有了答案:Arraysmisbehaving(1个回答)关闭6年前。是否应该这样,即我误解了,还是错误?a=Array.new(3,Array.new(3))a[1].fill('g')=>[["g","g","g"],["g","g","g"],["g","g","g"]]它不应该导致:=>[[nil,nil,nil],["g","g","g"],[nil,nil,nil]]

随机推荐