database - 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()
函数时发生错误
无法弄清楚是什么原因导致它请帮忙
解决方案
问题:
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
推荐阅读
- c++ - 如何避免 C++ 未定义行为欺骗 GoogleTest
- javascript - 如何使用 react js 和 asp.net core v3.0 下载文件
- c# - 多线程代码中的异步和等待问题
- php - CSS 和 Bootstrap 在 laravel5.8 中不起作用。我怎样才能解决这个问题?
- r - 无响应的滑块
- python - 由于 socket.py 中的错误,无法设置服务器
- c# - 如何解决 Azure Web 应用程序上的“请求标头过长”
- python - 尝试处理 IndentationError 异常
- kendo-ui-angular2 - 按下带有文本框值的回车键后如何触发事件?
- python - 使用 pyserial 的 AT+CIMI 命令导致空字符串