download201401 2017-08-15 21:06 采纳率: 0%
浏览 123
已采纳

Laravel模型不起作用

I'm trying to create post page with comments; however, it's not working when I add the comment to a post because the system doesn't recognize the post id. What I'm I doing wrong that it doesn't know that the post_id is equal to $post_id

I'm getting the following error:

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))

COMMENTS 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', 'CommentController@store');

CONTROLLER

public function store(Post $post)
{
    $post->addComment(request('body'));

    return back();
}

COMMENT MODEL

class Comment extends Model
{
    protected $fillable = ['body'];

    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

POST MODEL

class Post extends Model
{
    public function addComment($body)
    {
        Comment::create([
            'body' => $body,
            'post_id' => $this->id
        ]);
    }

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}
  • 写回答

3条回答 默认 最新

  • douwen2072 2017-08-15 21:09
    关注

    post_id isn't in fillable array:

    class Comment extends Model
    {
        protected $fillable = ['body', 'post_id']; //<---
        ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 请求分析基于spring boot+vue的前后端分离的项目
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?