【问题标题】:Integrity constraint vialations违反完整性约束
【发布时间】:2020-01-14 04:15:48
【问题描述】:

我正在尝试使用 drupal-8 将数据插入到 redirect 模块(表:redirect)中的数据库中。

当我第一次插入数据时它工作正常,但是当我再次插入数据时,数据已插入数据库但出现此错误。

function import_redirects($redirects) {
    foreach ($redirects as $from_url => $to_url) {
        Redirect::create([
            'redirect_source' => $from_url,
            'redirect_redirect' => 'internal:/'.$to_url,
            'language' => 'und',
            'status_code' => '301',
            'redirect_redirect__title' => NULL,
        ])->save();
    }
}

错误:

The website encountered an unexpected error. Please try again later.
Drupal\Core\Entity\EntityStorageException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'PBx-Sq7RCoQmsJVK-L3pYMpLiKaiyoACLU0atNt6qfE' for key 'hash': INSERT INTO {redirect} (type, uuid, language, hash, uid,` redirect_source__path, redirect_source__query, redirect_redirect__uri, redirect_redirect__title, redirect_redirect__options, status_code, created) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11); Array

【问题讨论】:

    标签: mysql drupal-8


    【解决方案1】:

    如果您尝试再次插入相同的条目,它将以相同的散列结束,该散列必须是唯一的。

    您应该检查该条目是否已经存在,如果不存在,则插入它,如果存在,则没有理由再次插入它。

    【讨论】:

    • 那么如何让它独一无二..我该怎么办
    • @afridi 请参阅我回答的第二段。如果它已经存在于数据库中,则没有理由再次插入它。
    猜你喜欢
    • 2021-12-13
    • 2017-10-01
    • 2019-04-12
    • 1970-01-01
    • 2020-04-08
    • 2016-04-13
    • 2019-10-20
    相关资源
    最近更新 更多