当用户注册时,每个用户都会收到一个存储在数据库中的七位数代码。每个代码都必须是唯一的,并且不能再次创建。如何确保存储的每个代码都是唯一的,并且在创建现有代码时不会出现错误消息?
函数
$randomstring = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyz"), 0, 7);表格
Schema::create('invites', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->text('greeting')->nullable();
$table->string('url')->unique();
$table->timestamps();
});发布于 2018-10-04 03:40:40
我会在while循环中使用doesntExist:
while (true) {
$randomstring = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyz"), 0, 7);
if (Invite::where('code', $randomstring)->doesntExist()) {
Invite::create([
...
'code' => $randomstring,
...
]);
break;
}
}发布于 2018-10-04 03:38:21
使用firstOrCreate()函数。
文档:https://laravel.com/docs/5.7/eloquent#other-creation-methods
https://stackoverflow.com/questions/52634442
复制相似问题