我正在尝试创建包含评论的帖子页面;但是,当我将评论添加到帖子时,它不起作用,因为系统无法识别帖子ID。我错误的是它不知道post_id等于$ post_id
我收到以下错误:
SQLSTATE [HY000]:常规错误:1364字段'post_id'没有默认值(SQL:插入
comments
body
,updated_at
,{{1} })值(这是测试评论,2017-08-15 19:51:47,2017-08-15 19:51:47))
评论表格
created_at
ROUTE
<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>
CONTROLLER
Route::post('/posts/{post}/comments', 'CommentController@store');
评论模型
public function store(Post $post)
{
$post->addComment(request('body'));
return back();
}
POST MODEL
class Comment extends Model
{
protected $fillable = ['body'];
public function post()
{
return $this->belongsTo(Post::class);
}
}
答案 0 :(得分:4)
post_id
不属于可填充数组:
class Comment extends Model
{
protected $fillable = ['body', 'post_id']; //<---
...
}
答案 1 :(得分:0)
确保你的post_id是自动增量或可以是“null”。这个错误说post_id没有值,不能默认。
从代码的外观看,post_id是你的主键,但没有设置为自动增量
答案 2 :(得分:0)
我明白了,你的控制器功能还不知道你说的是什么帖子。你需要使用从你的表单返回的帖子ID并找到帖子然后你可以保存这样的新评论
$ ansible-playbook test_sequenceeasy.yml
[WARNING]: log file at '{{planfile | dirname}}/AnsibleLog.txt' is not writeable and we cannot create it, aborting
PLAY [localhost] ***************************************************************
TASK [debug] *******************************************************************
ok: [localhost] => {
"listA[0]": "a"
}
TASK [debug] *******************************************************************
ok: [localhost] => {
"listB": []
}
TASK [debug] *******************************************************************
ok: [localhost] => {
"listC": []
}
TASK [set_fact] ****************************************************************
fatal: [localhost]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'list object' has no attribute u'0'\n\nThe error appears to have been in '/apps/infra/Tools/Ansible_WLNMiddleware/test_sequenceeasy.yml': line 17, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n var: listC\n - set_fact:\n ^ here\n"}
NO MORE HOSTS LEFT *************************************************************
[WARNING]: Could not create retry file 'test_sequenceeasy.retry'. [Errno 2] No such file or directory: ''
如Laravel Docs 5.4 Eloquent所示,它会为您填写内容。
此外,如果我没记错的话,您不需要将['post_id']添加到您的可填写字段数组中。
可以使用“列修饰符”解决SQL错误。 (见下文)
$comment = new App\Comment(['message' => 'A new comment.']);
$post = App\Post::find(1);
$post->comments()->save($comment);