如何将 Laravel 上的评论关联到用户?
How to associate comments to users on Laravel?
public function store(Post $post)
{
$this->validate(request(), ['body' => 'required|min:2']);
$post->addComment(request('body'));
return back();
}
这是我的代码
我有这个错误
SQLSTATE[HY000]: 一般错误: 1364 字段 'user_id' 没有默认值 (SQL: 插入到 comments
(body
, post_id
, updated_at
, created_at
) 值 (ewrtyuttrew, 1, 2018-02-15 15:44:17, 2018-02-15 15:44:17))
您需要添加手动创建评论的用户。例如:
public function addComment(string $body)
{
$this->comments()->create(['body' => $body, 'user_id' => auth()->id()]);
}
字段'user_id'
打开 phpmyadmin 并打开评论 table 然后在
之后
字段'user_id' =>自增和主键添加
试试这个我解决了这类问题,谢谢
在您的 User 模型中,您可以将关系定义为:
public function comments() {
return $this->hasMany(Comment::class);
}
因此,如果用户是登录用户,那么您可以使用 Auth 门面检索它:
$user = Auth::user();
那么你可以简单地做:
$user->comments()->save(new Comment(request('body'));
请注意,您必须在 Comment 模型上设置 "fillable" 字段才能允许动态创建。
public function store(Post $post)
{
$this->validate(request(), ['body' => 'required|min:2']);
$post->addComment(request('body'));
return back();
}
这是我的代码
我有这个错误
SQLSTATE[HY000]: 一般错误: 1364 字段 'user_id' 没有默认值 (SQL: 插入到 comments
(body
, post_id
, updated_at
, created_at
) 值 (ewrtyuttrew, 1, 2018-02-15 15:44:17, 2018-02-15 15:44:17))
您需要添加手动创建评论的用户。例如:
public function addComment(string $body)
{
$this->comments()->create(['body' => $body, 'user_id' => auth()->id()]);
}
字段'user_id'
打开 phpmyadmin 并打开评论 table 然后在
之后字段'user_id' =>自增和主键添加
试试这个我解决了这类问题,谢谢
在您的 User 模型中,您可以将关系定义为:
public function comments() {
return $this->hasMany(Comment::class);
}
因此,如果用户是登录用户,那么您可以使用 Auth 门面检索它:
$user = Auth::user();
那么你可以简单地做:
$user->comments()->save(new Comment(request('body'));
请注意,您必须在 Comment 模型上设置 "fillable" 字段才能允许动态创建。