Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何将用户id添加到多态关系?_Php_Laravel_Laravel 5 - Fatal编程技术网

Php 如何将用户id添加到多态关系?

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

我的帖子、视频和评论之间存在多态关系

我想补充的是谁在帖子/评论或视频/评论之间建立了关系。本质上是向comments表添加一个userId

目前我有

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语句,只有在有用户的情况下才能这样做。