[英]How do I add a user_id to a polymorphic relationship?
I have a polymorphic relationship between Posts, Videos and Comments. 我在帖子,视频和评论之间有多态关系。
What I want to add is who made the relationship between the Posts/Comments or Videos/Comments. 我要添加的是谁在帖子/评论或视频/评论之间建立了关系。 Essentially add a userId to the comments table. 本质上,将userId添加到注释表。
Currently I have 目前我有
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
I can not figure out how to use eloquent to achieve what I want. 我无法弄清楚如何用雄辩的语言实现我想要的。 I have followed the docs and added the morph
relationships as per the docs but I can't seem to find a way for the user_id to be saved into the comments table as well. 我按照文档并添加morph
关系,因为每文档 ,但我似乎无法找到的USER_ID要保存到的意见表,以及一种方式。
How do I use eloquent to also save the user_id each time the polymorphic relationship is created? 每次创建多态关系时,我如何使用雄辩的方式也保存user_id?
You can use Model Events to set data on new records right before they are saved to the database. 您可以使用模型事件在新记录上设置数据,然后再将其保存到数据库中。 Within your Comment
model, add the following method: 在您的Comment
模型中,添加以下方法:
public static function boot() {
parent::boot();
static::creating(function($comment) {
$comment->user_id = auth()->id();
});
}
In you controller for creating comments: 在用于创建评论的控制器中:
$newComment = new Comment;
...
$newComment->user_id = Auth::user()->id;
$newComment->save();
How do you create the Comment? 您如何创建评论? If you do something like Comment::create(['user_id' => auth()->user->id])
. 如果您执行类似Comment::create(['user_id' => auth()->user->id])
。 Remeber to have added user_id
to your fillable array on the Comment model. 请记住已将user_id
添加到Comment模型的可填充数组中。
Else you can use 否则你可以使用
$comment = new Comment();
$comment->user_id = auth()->user->id;
$comment->save()
etc...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.