【发布时间】:2018-02-03 17:03:20
【问题描述】:
当我想在关系后对我的帖子添加评论时收到此错误
SQLSTATE[23000]:完整性约束违规:1048 列“Posts_ID”不能为空(SQL:插入
Comment(Comment,posts_id,updated_at,created_at)值(dwa,, 2018-02-03 16:47:58, 2018-02-03 16:47:58))
路线:
Route::get('/showpost/{showpost}/create/comment', function($ID) {
$showpost = Posts::find($ID);
return view('createcomment', compact('showpost'));
});
Route::post('/showpost/{showpost}/create/comment', 'PostController@storecm');
控制器:
public function storecm(Posts $showpost, Request $request)
{
$showpost->Comment()->create($request->all());
}
查看:
<form action="{{ action('PostController@storecm', $showpost->ID) }}" method="post">
{!! csrf_field() !!}
<label>Comment :</label>
<input type="text" name="Comment" id="Comment">
<button type="submit" class="btn btn-success">Add Comment</button>
</form>
【问题讨论】:
-
几个问题:1)您的
Posts模型中是否设置了comment()关系? 2)如果没有,请添加一个。如果你这样做了,那么你可能需要将外键指定为posts_id(复数),因为默认情况下它会假设post_id(单数)。此外,您可能想查看 MVC 命名约定。例如,模型类名称通常是单数的(它们代表事物的一个实例)。如果您遵循这些,那么您的关系将更有可能在没有修改的情况下运作。 (laravel.com/docs/5.5/eloquent#eloquent-model-conventions)
标签: laravel