Php 如何将用户id添加到多态关系?
我的帖子、视频和评论之间存在多态关系 我想补充的是谁在帖子/评论或视频/评论之间建立了关系。本质上是向comments表添加一个userId 目前我有Php 如何将用户id添加到多态关系?,php,laravel,laravel-5,Php,Laravel,Laravel 5,我的帖子、视频和评论之间存在多态关系 我想补充的是谁在帖子/评论或视频/评论之间建立了关系。本质上是向comments表添加一个userId 目前我有 user id - integer name - string posts id - integer title - string body - text videos id - integer title - string url - string comments
user
id - integer
name - string
posts
id - integer
title - string
body - text
videos
id - integer
title - string
url - string
comments
id - integer
body - text
commentable_id - integer
commentable_type - string
user_id - integer
我想不出如何用雄辩来达到我的目的。我已经按照文档的要求添加了morph
关系,但是我似乎也找不到将用户id保存到comments表中的方法
如何在每次创建多态关系时使用eloquent来保存用户id?您可以在新记录保存到数据库之前使用它来设置新记录的数据。在您的注释
模型中,添加以下方法:
public static function boot() {
parent::boot();
static::creating(function($comment) {
$comment->user_id = auth()->id();
});
}
在用于创建注释的控制器中:
$newComment = new Comment;
...
$newComment->user_id = Auth::user()->id;
$newComment->save();
如何创建注释?如果您执行类似于
Comment::create(['user\u id'=>auth()->user->id])
。请记住已将user\u id
添加到注释模型上的可填充数组中
你还可以用别的
$comment = new Comment();
$comment->user_id = auth()->user->id;
$comment->save()
etc...
非常感谢,我遇到的问题是,当我编写测试时,我必须添加一个if语句,只有在有用户的情况下才能这样做。