我正在按照laravel教程创建一个表单,用user_id在帖子上创建评论。我似乎无法理解我如何传递user_id。
Post
模型
class Post extends Model
{
protected $guarded = [];
public function comments()
{
return $this->hasMany(Comment::class);
}
public function addComment($body)
{
$this->comments()->create(compact('body'));
}
public function user()
{
return $this->belongsTo(User::class);
}
}
Comment
模型
class Comment extends Model
{
protected $guarded = [];
public function post()
{
$this->belongsTo(Post::class);
}
public function user()
{
$this->belongsTo(User::class);
}
}
User
模型
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts()
{
return $this->hasMany(Post::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function publish(Post $post)
{
$this->posts()->save($post);
}
}
CommentsController.php
class CommentsController extends Controller
{
public function store(Post $post)
{
$this->validate(request(), ['body' => 'required|min:2']);
$post->addComment(request('body'));
return back();
}
}
如您所见,我在->addComment
模型中调用Post
来添加评论。它工作得很好,直到我将user_id添加到Comments
表。存储用户ID的最佳方法是什么?我无法让它发挥作用。
答案 0 :(得分:1)
更新您的addComment
方法:
public function addComment($body)
{
$user_id = Auth::user()->id;
$this->comments()->create(compact('body', 'user_id'));
}
PS:假设用户已通过身份验证。
<强>更新强>
public function addComment($body)
{
$comment = new Comment;
$comment->fill(compact('body'));
$this->comments()->save($comment);
}
在没有保存的情况下创建评论的新实例,您只需要在帖子中保存评论,因为帖子已经属于用户
答案 1 :(得分:0)
无需手动处理ID,让您雄辩地为您处理:
$user = Auth::user(); // or $request->user()
$user->comments()->save(new Comment());