如何解决 Laravel 5.7 中违反完整性约束的问题?
How to solve integrity constraint violation in Laravel 5.7?
我收到以下错误:SQLSTATE[23000]:违反完整性约束:1048 列 'user_id' 不能为空(SQL:插入 answers
(body
, user_id
, question_id
, updated_at
, created_at
)
我正在尝试使用 Laravel 提交对表单的回答,但出现上述错误。首先,我检查了我的答案 table 中的模式, user_id 被正确定义:
public function up()
{
Schema::create('answers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedInteger('question_id');
$table->unsignedInteger('user_id');
$table->text('body');
$table->integer('votes_count')->default(0);
$table->timestamps();
});
}
接下来我将此代码添加到我的 AnswersController.php 以验证代码并在提交答案后重定向:
public function store(Question $question, Request $request)
{
$request->validate([
'body' => 'required'
]);
$question->answers()->create(['body' => $request->body, 'user_id' => \Auth::id()]);
return back()->with('success', "Your answer has been submitted successfully");
}
我将答案 class 导入到我的 AnswersController.php 中,我还在 Answer.php 模型中将正文和 user_id 字段设为可填写:
protected $fillable = ['body', 'user_id'];
当我单击表单上的提交按钮时,出现如上所示的 SQL 状态错误。 user_id 是我的数据库答案中的有效字段 table。我似乎无法弄清楚。
您的代码看起来不错。但错误非常简单:您没有得到 user_id
。 IE 您正在尝试创建一个答案枢轴,调用 user_id
从非对象创建。 \Auth::id() 为空或无法识别您想要的内容。改为调用用户对象。
试试这个:
$question->answers()->create(['body' => $request->body, 'user_id' => \Auth::user()->id]);
还要确保您确实有一个用户:使用 auth 中间件通过路由将表单发回:
Route::group(['middleware' => ['auth']], function () {
Route::resource('questions.answers', 'AnswersController');
// Any other routes where you want a user
}
我收到以下错误:SQLSTATE[23000]:违反完整性约束:1048 列 'user_id' 不能为空(SQL:插入 answers
(body
, user_id
, question_id
, updated_at
, created_at
)
我正在尝试使用 Laravel 提交对表单的回答,但出现上述错误。首先,我检查了我的答案 table 中的模式, user_id 被正确定义:
public function up()
{
Schema::create('answers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedInteger('question_id');
$table->unsignedInteger('user_id');
$table->text('body');
$table->integer('votes_count')->default(0);
$table->timestamps();
});
}
接下来我将此代码添加到我的 AnswersController.php 以验证代码并在提交答案后重定向:
public function store(Question $question, Request $request)
{
$request->validate([
'body' => 'required'
]);
$question->answers()->create(['body' => $request->body, 'user_id' => \Auth::id()]);
return back()->with('success', "Your answer has been submitted successfully");
}
我将答案 class 导入到我的 AnswersController.php 中,我还在 Answer.php 模型中将正文和 user_id 字段设为可填写:
protected $fillable = ['body', 'user_id'];
当我单击表单上的提交按钮时,出现如上所示的 SQL 状态错误。 user_id 是我的数据库答案中的有效字段 table。我似乎无法弄清楚。
您的代码看起来不错。但错误非常简单:您没有得到 user_id
。 IE 您正在尝试创建一个答案枢轴,调用 user_id
从非对象创建。 \Auth::id() 为空或无法识别您想要的内容。改为调用用户对象。
试试这个:
$question->answers()->create(['body' => $request->body, 'user_id' => \Auth::user()->id]);
还要确保您确实有一个用户:使用 auth 中间件通过路由将表单发回:
Route::group(['middleware' => ['auth']], function () {
Route::resource('questions.answers', 'AnswersController');
// Any other routes where you want a user
}