【问题标题】:SQLSTATE[HY000]: General error: 1364 Field 'img' doesn't have a default value (SQL: insert into `users`SQLSTATE [HY000]:一般错误:1364 字段“img”没有默认值(SQL:插入“用户”
【发布时间】:2019-01-15 03:29:27
【问题描述】:

错误的原因是什么?这是在注册时更改默认代码后发生的。请带我去

SQLSTATE[HY000]: General error: 1364 Field 'img' doesn't have a default value (SQL: insert into `users` (`username`, `password`, `role`, `updated_at`, `created_at`) values (aaaaaaa, .....G, user, 2019-01-14 16:40:05, 2019-01-14 16:40:05))

protected function validator(array $data)
    {
        return Validator::make($data, [
            'username' => 'required|string|check_username|max:255|unique_username',
            'password' => 'required|string|min:6',
            'captcha'=>'required|captcha'
        ],[],[
            'username'=>'user',
            'password'=>'pass',
            'captcha'=>'cap',
            'img'=>'profile',
            'fnamelname'=>'fnamelname',



        ]);
    }


protected function create(array $data)
{
    return User::create([
        'username' => $data['username'],
        'password' => bcrypt($data['password']),
        'role'=>'user'
    ]);
}

【问题讨论】:

  • img 列没有默认值,如果不传递任何值,则无法创建记录。请分享您的用户创建代码。

标签: laravel


【解决方案1】:

试试这个:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('username')->unique();
        $table->string('password');
        $table->string('img')->default(1);
        $table->string('fnamelname');
        $table->string('role');
        $table->rememberToken();
        $table->timestamps();
    });
}

编辑:

这是一个更好的版本

$table->string('img')->nullable();

【讨论】:

  • 这会将 img 字段默认设置为 1,这会引入一个奇怪的值,之后您将不得不对其进行管理。您最好将该字段设置为可为空。
  • $table->string('img')->nullable(); 已更新
【解决方案2】:
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('username')->unique();
        $table->string('password');
        $table->string('img');
        $table->string('fnamelname');
        $table->string('role');
        $table->rememberToken();
        $table->timestamps();
    });
}

/**

【讨论】:

  • 这是您最初的迁移吗?如果是这样,请编辑您的问题并将其清楚地插入其中。
【解决方案3】:

如果img 字段是可选的,您的数据模型应该清楚地反映该意图。

在您的迁移中:

 $table->string('img')->nullable();

会将此列设置为可为空,因此您无需显式设置值即可创建记录。

https://laravel.com/docs/5.0/schema#adding-columns

另外,您最好使用 BLOB 类型而不是字符串来存储图像等二进制内容。但这是另一个话题。

【讨论】:

    猜你喜欢
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 2021-05-23
    • 2019-05-09
    • 2019-09-10
    • 2021-01-04
    • 2020-09-06
    相关资源
    最近更新 更多