我正在嘗試創建帶有註釋的帖子頁面;但是,由於系統無法識別帖子ID,因此在向帖子添加評論時,它無法正常工作。我是我做錯了,它不知道POST_ID等於$ POST_IDLaravel模型不起作用
,我發現了以下錯誤:
SQLSTATE[HY000]: General error: 1364 Field 'post_id' doesn't have a default value (SQL: insert into
comments
(body
,updated_at
,created_at
) values (This is a test comment, 2017-08-15 19:51:47, 2017-08-15 19:51:47))
評論FORM
<div class="well">
<h4>Leave a Comment:</h4>
<form role="form" method="post" action="{{ $post->id }}/comments">
{{ csrf_field() }}
<div class="form-group">
<textarea name="body" class="form-control" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
ROUTE
Route::post('/posts/{post}/comments', '[email protected]');
控制器
public function store(Post $post)
{
$post->addComment(request('body'));
return back();
}
評論模型
class Comment extends Model
{
protected $fillable = ['body'];
public function post()
{
return $this->belongsTo(Post::class);
}
}
樁模型
class Post extends Model
{
public function addComment($body)
{
Comment::create([
'body' => $body,
'post_id' => $this->id
]);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}
嘗試在後模型添加POST_ID和身體爲可填寫陣列 – mattchambers