【问题标题】:Default value for username in SQL databaseSQL 数据库中用户名的默认值
【发布时间】:2021-02-17 05:27:42
【问题描述】:

我正在编写一个 Laravel 应用程序,为了在 sqlite 中进行测试,您需要为迁移中的所有字段指定 ->nullable() 或 ->default("123")。这让我感到困惑,因为我的用户迁移目前看起来像这样:

public function up() {
    Schema::create('users', function($table) {
        $table->increments('id');
        $table->integer('role_id');
        $table->string('username')->unique();
        $table->string('password');
        $table->string('name');
        $table->string('email');
        $table->integer('max_locations');
        $table->string('auth_token');
        $table->string('remember_token', 100);
        $table->timestamps();
    });
}

其中许多既不添加 ->default("123") 也不添加 ->nullable() 毫无意义。用户名就是一个很好的例子,我不能在数据库中将 null 作为用户名,但是如果我设置了一个默认值,也不会起作用。没有添加用户名的第二个用户将使用默认用户名,并且由于用户名必须是唯一的,因此会引发异常。

目前我没有指定任何内容,SQL 通过为所有这些字段提供默认值“无”来解决这个问题。可以在这里以某种方式添加吗?如果没有,我的用户名应该有默认值还是可以为空?

【问题讨论】:

    标签: php mysql laravel default nullable


    【解决方案1】:

    您不能有具有默认 NULL 值的 NOT NULL 列。如果您不希望列可以为空,只需像这样指定默认值:

    $table->string('username')->unique()->default('');
    

    在您的验证过程中,您当然不会让空值,所以没关系。

    【讨论】:

    • 是的,这是我觉得最有道理的,我只是测试一下其他人提到的内容。
    • 我已经测试了一下,这对我来说效果最好。感谢您的帮助!
    【解决方案2】:

    试试这个

    $table->string('username')->unique()->default($value);
    

    【讨论】:

    • 这是什么?我不明白,$value 是从哪里来的?
    • 我认为 $value 只是一个占位符值。
    • $value 是您的期望值,例如“admin”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    相关资源
    最近更新 更多