[英]SQLSTATE[HY000]: General error: 1364 Field 'photo' doesn't have a default value in laravel 5.5
[英]Laravel 8: SQLSTATE[HY000]: General error: 1364 Field 'answer' doesn't have a default value
我正在與 Laravel 8 合作開發我的在線論壇項目。 而在這個論壇里,基本上用戶可以回答問題。
因此,在 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();
}
請注意, $id
變量是問題 ID。
但是現在的問題是,每當我嘗試添加答案時,都會收到此錯誤:
Illuminate\Database\QueryException SQLSTATE[HY000]:一般錯誤:
1364 字段“答案”沒有默認值
這背后的形式在這里:
<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>
這也是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();
});
}
如果你想查看模型之間的關系,這里是:
Question.php:
public function answers()
{
return $this->hasMany(Answer::class);
}
用戶.php:
public function answers()
{
return $this->hasMany(Answer::class);
}
那么這里出了什么問題,我該如何解決這個問題?
如果您就此分享您的想法或建議,我將不勝感激...
提前致謝。
在您的答案 Model 中,確保您的$fillable
fillable 屬性具有正確的屬性:
class Answer extends Model
{
protected $fillable = ['answer','user_id','question_id'];
....
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.