SQLSTATE [23000]:完整性约束违规:19 NOT NULL约束失败:

时间:2017-10-09 03:44:22

标签: php laravel laravel-5.5

尝试在laravel上创建待办事项列表应用程序但是当我尝试单击按钮创建新的待办事项列表时,我收到此错误:

[viewA removeFromSuperView];
[self.view addSubview:viewA];

这是我的控制器:

SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: tasks.description (SQL: insert into "tasks" ("description", "user_id", "updated_at", "created_at") values (, 1, 2017-10-09 03:28:35, 2017-10-09 03:28:35))

这是我的任务模型:

命名空间App;

使用Illuminate \ Database \ Eloquent \ Model;

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    public function tasks()
    {
        return $this->hasMany(Task::class);
    }

    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

这是用户的模型:

class Task extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }

}

以下是观点:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    public function tasks()
    {
        return $this->hasMany(Task::class);
    }

    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

似乎无法弄清问题,谷歌似乎也没有想法。

5 个答案:

答案 0 :(得分:1)

您获得的错误意味着表中有一些列没有空约束,并且您正在插入/更新空值。

要纠正它:

1)为列提供一个非空值并添加到下面的任务模型代码段中:

protected $fillable = [
    'description'];

2)通过编写:

,使列在迁移文件的表中可为空
$table->('description')->nullable();

从其任务模型中删除您可以为空的列名(在表中)。

=&GT;通过删除所有表来清空phpmyadmin中的数据库。

=&GT;运行命令:php artisan migrate

=&GT;尝试重新执行操作。

答案 1 :(得分:1)

就我而言,我输入了之前插入的相同唯一 ID,在删除该特定记录后,它起作用了。此外,如果您打开了 SQLite 数据库浏览器,请尝试完全关闭该浏览器 {“PDOException: SQLSTATE[HY000]: General error: 5 database is locked”,此错误随后又回来了}。它对我有用。我知道这是一个菜鸟解决方案,但认为分享这可能会有所帮助。

答案 2 :(得分:0)

因为tasks表中的描述值为null。

以下是解决问题的方法 -

  1. 如果description可以为null,则可以使其从数据库表结构中为空。

  2. 在模型上添加$fillable属性 -

    class Task extends Model
    {
        //add this
        protected $fillable = ["description", "user_id"];
    
        public function user()
        {
            return $this->belongsTo(User::class);
        }
    }
    

答案 3 :(得分:0)

在“任务”模型中,尝试添加:

protected $fillable = ["description", "user_id"];

答案 4 :(得分:0)

您需要刷新数据库表。您的模型或迁移中不存在数据库中的column。并且您没有输入该字段的数据。我只是删除了所有表并进行了迁移。 php artisan migrate:fresh