私はコメント付き投稿ページを作成しようとしています。しかし、システムが投稿IDを認識しないため、投稿にコメントを追加すると機能しません。Laravelモデルが動作しません
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))
コメントフォーム
<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>
:それはpost_idのは、私は次のエラーを取得しています$ post_idの
に等しいことを知らないことを私は私が間違ってやっています
ROUTE
Route::post('/posts/{post}/comments', '[email protected]');
CONTROLLER
public function store(Post $post)
{
$post->addComment(request('body'));
return back();
}
COMMENTモデル
class Comment extends Model
{
protected $fillable = ['body'];
public function post()
{
return $this->belongsTo(Post::class);
}
}
Postモデル
class Post extends Model
{
public function addComment($body)
{
Comment::create([
'body' => $body,
'post_id' => $this->id
]);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}
(下記参照) – mattchambers