Laravel模型不起作用
问题描述:
我正在尝试创建带有注释的帖子页面;但是,由于系统无法识别帖子ID,因此在向帖子添加评论时,它无法正常工作。我是我做错了,它不知道POST_ID等于$ POST_IDLaravel模型不起作用
,我发现了以下错误:
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))
评论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', '[email protected]');
控制器
public function store(Post $post)
{
$post->addComment(request('body'));
return back();
}
评论模型
class Comment extends Model
{
protected $fillable = ['body'];
public function post()
{
return $this->belongsTo(Post::class);
}
}
桩模型
class Post extends Model
{
public function addComment($body)
{
Comment::create([
'body' => $body,
'post_id' => $this->id
]);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}
答
post_id
不是可填充数组:
class Comment extends Model
{
protected $fillable = ['body', 'post_id']; //<---
...
}
答
在你的表在MySQL确保您POST_ID是自动增量或可以为“空”。这个错误是说post_id没有价值,不能默认。
从代码POST_ID的外观为您的主键而不是设置为自动增量
答
我明白了,你的控制器功能doen't知道什么帖子你谈论。您需要使用后的ID来从形式回来,找到后,你可以保存这样
$comment = new App\Comment(['message' => 'A new comment.']);
$post = App\Post::find(1);
$post->comments()->save($comment);
新注释如Laravel Docs 5.4 Eloquent表明,它会填满ID在你。
此外,如果我没有记错,你不需要添加['post_id']到你的可填充字段数组。
SQL错误可以通过使用“列修改器”来解决。 (见下文)
Schema::table('users', function (Blueprint $table) {
$table->string('email')->nullable();
});
尝试在后模型添加POST_ID和身体为可填写阵列 – mattchambers