And*_*ero 0 php laravel laravel-5.4
我正在尝试创建带有评论的帖子页面;但是,当我将评论添加到帖子时它不起作用,因为系统无法识别帖子 ID。我做错了什么,它不知道 post_id 等于 $post_id
我收到以下错误:
SQLSTATE[HY000]: General error: 1364 Field 'post_id' does not 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>
Run Code Online (Sandbox Code Playgroud)
路线
Route::post('/posts/{post}/comments', 'CommentController@store');
Run Code Online (Sandbox Code Playgroud)
控制器
public function store(Post $post)
{
$post->addComment(request('body'));
return back();
}
Run Code Online (Sandbox Code Playgroud)
评论模型
class Comment extends Model
{
protected $fillable = ['body'];
public function post()
{
return $this->belongsTo(Post::class);
}
}
Run Code Online (Sandbox Code Playgroud)
后模型
class Post extends Model
{
public function addComment($body)
{
Comment::create([
'body' => $body,
'post_id' => $this->id
]);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}
Run Code Online (Sandbox Code Playgroud)
post_id 不在可填充数组中:
class Comment extends Model
{
protected $fillable = ['body', 'post_id']; //<---
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3152 次 |
| 最近记录: |