【问题标题】:check unique - laravel检查唯一性 - laravel
【发布时间】:2018-10-03 19:34:06
【问题描述】:

当用户注册时,每个用户都会收到一个存储在数据库中的七位数代码。每个代码必须是唯一的,并且不得再次创建。 如何确保存储的每个代码都是唯一的,并且在创建现有代码时不会出现错误消息?

功能

 $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();
        });

【问题讨论】:

  • 七位代码与用户有什么关系?一个代码可以多次使用吗?

标签: laravel function random unique


【解决方案1】:

我会在 while 循环中使用 doesntExist

while (true) {
    $randomstring = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyz"), 0, 7);
    if (Invite::where('code', $randomstring)->doesntExist()) {
        Invite::create([
            ...
            'code' => $randomstring,
            ...
        ]);
        break;
    }
}

【讨论】:

  • 如果生成的代码存在,你的代码怎么办?
  • 它只是不断循环并创建新的随机字符串,直到创建一个不存在的字符串。
  • 我收到一条错误消息:调用未定义的方法 Illuminate\Database\Query\Builder::doesntExists()
  • 我也可以使用:if (Invite::where('url','!=', $randomstring))
  • 这是doesntExist() 不是doesntExists()
【解决方案2】:

使用firstOrCreate() 函数。

文档:https://laravel.com/docs/5.7/eloquent#other-creation-methods

【讨论】:

    猜你喜欢
    • 2014-04-15
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多