laravel - php向mysql執行insert時,提示“mysql duplicate key”,如何處理?

來源:互聯網
上載者:User
前提:【laravel4】伺服器端提供介面全部採用非同步方式調用,資料表有唯一鍵
情境:在並發請求處理中,mysql資料庫會出現“ Integrity constraint violation: 1062 Duplicate entry ”,如兩個使用者同時請求註冊email

$ret = User::create(array(    'email' => "nick@nick.com"));

我想讓這兩個並發請求都成功返回,並返回Email,如何規避掉索引值重複。
目前有以下幾種:
1)插入前,使用select查詢,但這個並不能解決問題。
2)使用insert ignore
3)使用insert on duplicate key
4)直接try catch
哪種處理方案會好些?

回複內容:

前提:【laravel4】伺服器端提供介面全部採用非同步方式調用,資料表有唯一鍵
情境:在並發請求處理中,mysql資料庫會出現“ Integrity constraint violation: 1062 Duplicate entry ”,如兩個使用者同時請求註冊email

$ret = User::create(array(    'email' => "nick@nick.com"));

我想讓這兩個並發請求都成功返回,並返回Email,如何規避掉索引值重複。
目前有以下幾種:
1)插入前,使用select查詢,但這個並不能解決問題。
2)使用insert ignore
3)使用insert on duplicate key
4)直接try catch
哪種處理方案會好些?

那就要看你的需求了,出現Duplicate entry這個錯誤是因為主鍵有重複,如果是以uid為主鍵的話,那麼要考慮uid產生演算法是否有問題,或者是否重複註冊了

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.