首页 > 解决方案 > SQLSTATE [23000]:违反完整性约束:19 NOT NULL 即使在使必填字段为空之后

问题描述

我已将所有必填字段设为空,但我仍然收到此错误

SQLSTATE [23000]:完整性约束违规:19 NOT NULL 约束失败:public_problems.name(SQL:插入“public_problems”(“answer”、“helper_id”、“helper_name”、“updated_at”、“created_at”)值(嘿Bro Everythings Gonna be Alright, 2, kakashi, 2020-07-30 07:35:05, 2020-07-30 07:35:05))

这是我的数据库:-

public function up()
    {
        Schema::create('public_problems', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('user_id')->unsigned();
            $table->text('answer')->nullable();
            $table->integer('helper_id')->unsigned()->nullable();
            $table->string('helper_name')->nullable();
            $table->string('title');
            $table->text('problem');
            $table->string('filled_by');

            $table->timestamps();
        });
    }

模型:-

class PublicProblem extends Model
{
    protected $fillable = ['name', 'user_id', 'title', 'problem', 'filled_by', 'helper_id', 'answer', 'helper_name'];

}

我已将此字段分为 2 个功能,它们是:-
控制器

public function store(Request $request)
    {
        $data = request()->validate([
        'title' => 'required',
        'problem' => 'required',

      ]);
         PublicProblem::create([
            'title'=>$data['title'],
            'problem'=>$data['problem'],
            'name'=>Auth::user()->name,
            'user_id'=>Auth::user()->id,
            'filled_by'=>Auth::user()->uuid,

          ]);
         return redirect('/home');
    }

public function answer(Request $request) //The Error Occurs when I try to execute this function 
    {
    

        $data = request()->validate([
            'answer' => 'required',
        ]);

        PublicProblem::create([
            'answer' => $data['answer'],
            'helper_id' => Auth::user()->id,
            'helper_name' => Auth::user()->name,
        ]);
        return redirect('/home');
    }

当我尝试执行answer()函数时发生错误
无法弄清楚是什么原因导致它请帮忙

标签: databaselaravelcontroller

解决方案


问题:

SQLSTATE [23000]:违反完整性约束:19 NOT NULL 约束失败:public_problems.name

解决方案:

数据库中的名称文件不可为空。如果要调用 create 方法,则必须添加'name' => 'someName'或将->nullable()约束添加到名称字段。

PublicProblem::create([
            'answer' => $data['answer'],
            'helper_id' => Auth::user()->id,
            'helper_name' => Auth::user()->name,
            'name' => 'someName',
        ]);

请注意:

您还有一些不可为空的字段,因此另一个字段可能会再次发生错误。(我在下面评论过)

$table->id();
$table->string('name'); //always needs a value
$table->integer('user_id')->unsigned(); //always needs a value
$table->text('answer')->nullable();
$table->integer('helper_id')->unsigned()->nullable();
$table->string('helper_name')->nullable();
$table->string('title'); //always need a value
$table->text('problem'); //always needs a value
$table->string('filled_by'); //always needs a value

推荐阅读