[英]Laravel 8: SQLSTATE[HY000]: General error: 1364 Field 'answer' doesn't have a default value
I'm working with Laravel 8 to develop my project which is an Online Forum.我正在与 Laravel 8 合作开发我的在线论坛项目。 And in this forum, basically users can answer to questions.而在这个论坛里,基本上用户可以回答问题。
So at the Controller, I put this for posting answers:因此,在 Controller 中,我将其用于发布答案:
public function PostAnswer($id)
{
$validate_data = Validator::make(request()->all(),[
'answer' => 'required',
])->validated();
$answer = Answer::create([
'answer' => $validate_data['answer'],
'user_id' => auth()->user()->id,
'question_id' => $id,
]);
return back();
}
Note that $id
variable is the question id.请注意, $id
变量是问题 ID。
But now the problem is whenever I try to add an answer, I get this error:但是现在的问题是,每当我尝试添加答案时,都会收到此错误:
Illuminate\Database\QueryException SQLSTATE[HY000]: General error: Illuminate\Database\QueryException SQLSTATE[HY000]:一般错误:
1364 Field 'answer' doesn't have a default value 1364 字段“答案”没有默认值
The form behind this goes here:这背后的形式在这里:
<form action="{{ route('questions.answers', $show->id) }}" method="POST">
@csrf
<textarea name="answer" id="answer" class="form-control" rows="7"></textarea
@error('answer')
<div class="text-red-500 mt-2 text-sm">
{{ $message }}
</div>
@enderror
<button type="submit" class="btn btn-primary">Submit</button>
</form>
And here is also the Migration of answers
table:这也是answers
表的迁移:
public function up()
{
Schema::create('answers', function (Blueprint $table) {
$table->id();
$table->text('answer');
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('question_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
}
If you want to look at relations between Models, here it is:如果你想查看模型之间的关系,这里是:
Question.php: Question.php:
public function answers()
{
return $this->hasMany(Answer::class);
}
User.php:用户.php:
public function answers()
{
return $this->hasMany(Answer::class);
}
So what is going wrong here, how can I fix this issue?那么这里出了什么问题,我该如何解决这个问题?
I would really appreciate if you share your idea or suggestion on this...如果您就此分享您的想法或建议,我将不胜感激...
Thanks in advance.提前致谢。
in your Answer Model, make sure you have $fillable
property with correct properties:在您的答案 Model 中,确保您的$fillable
fillable 属性具有正确的属性:
class Answer extends Model
{
protected $fillable = ['answer','user_id','question_id'];
....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.