用戶代碼已生成並且必須是唯一的。在此模型保存上執行重試邏輯的最簡單/最乾淨的方式是什麼?我想首先驗證生成的代碼,然後如果在用戶表中找不到它,則創建用戶(如果找到),循環以重試。那是什麼語法?由於模型保存的重試邏輯 - Laravel
public function create(array $data)
{
$user = User::create([
'user_name' => 'My user name',
'user_code' => bin2hex(openssl_random_pseudo_bytes(16))
]);
$user->save();
return $user;
}
謝謝。我喜歡! – user3489502
'bin2hex(openssl_random_pseudo_bytes(16))'這個函數能產生兩次相同的數字嗎?如果不是你如何獲得相同的條件使用'User :: where('user_code',$ code) - > get()'它每次生成的數字都不同於你插入數據庫''user_code'=> bin2hex openssl_random_pseudo_bytes(16))'@ marco-aurélio-deleu –
openssl_random_pseudo_bytes(16)生成一個隨機字符串,不一定是唯一的 – user3489502