SQLSTATE [23000]:完整性约束违规laravel 5.4

时间:2018-02-03 17:03:21

标签: laravel

当我想在关系

之后在我的帖子上添加评论时,我收到此错误
  

SQLSTATE [23000]:完整性约束违规:1048列' Posts_ID'不能为空(SQL:插入CommentCommentposts_idupdated_atcreated_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>

4 个答案:

答案 0 :(得分:0)

您在创建评论时遇到错误,因为$request->all()不包含posts_id字段,请在控制器中执行以下更改:

public function storecm(Posts $showpost, Request $request)
{
   $comment=new Comment();
   $comment->Comment=$request->input('Comment');
   $comment->posts_id=$showpost->ID;
   $comment->save();
}

答案 1 :(得分:0)

请检查您的评论模型,post_id可以更改吗?

Private $fillable =[
                     ‘post_id’,
                      …..
                    ];

您可以使用

$comment = $request->all();
$post->comments()->save($comment);

答案 2 :(得分:0)

请记住,在获取此错误时使用hasMany或hasOne时使用3个参数

    return $this->hasMany('App\Comment', 'Posts_ID', 'ID');
像这样......

答案 3 :(得分:0)

确保&#34; posts_id&#34;存在于可填写部分

下的模型

E.g

protected $ fillable = ['post_id',&#39; xyz&#39;,....];