【问题标题】:SQLSTATE[23000]: Integrity constraint violation laravel 5.4SQLSTATE [23000]:完整性约束违反 laravel 5.4
【发布时间】:2018-02-03 17:03:20
【问题描述】:

当我想在关系后对我的帖子添加评论时收到此错误

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>

【问题讨论】:

  • 几个问题:1)您的Posts 模型中是否设置了comment() 关系? 2)如果没有,请添加一个。如果你这样做了,那么你可能需要将外键指定为posts_id(复数),因为默认情况下它会假设post_id(单数)。此外,您可能想查看 MVC 命名约定。例如,模型类名称通常是单数的(它们代表事物的一个实例)。如果您遵循这些,那么您的关系将更有可能在没有修改的情况下运作。 (laravel.com/docs/5.5/eloquent#eloquent-model-conventions)

标签: laravel


【解决方案1】:

您在创建评论时遇到错误,因为 $request-&gt;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();
}

【讨论】:

  • 非常感谢,但我认为这不是标准方式!第一次插入并在更新该记录后我认为是错误的,你怎么看@Saurabh
【解决方案2】:

请检查您的评论模型 post_id 是否可以更改?

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

你可以使用

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

【讨论】:

    【解决方案3】:

    请记住,当使用 hasMany 或 hasOne 时出现此错误时使用 3 个参数

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

    像这样……

    【讨论】:

      【解决方案4】:

      确保“posts_id”出现在您的MODEL中可填写部分

      例如

      受保护的 $fillable = ['post_id','xyz',....];

      【讨论】:

        猜你喜欢
        • 2017-09-11
        • 2015-07-17
        • 2021-07-23
        • 2014-08-18
        • 2015-03-19
        • 2015-11-27
        • 2015-01-20
        • 2021-07-10
        相关资源
        最近更新 更多