简体   繁体   中英

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.

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.

How do I use eloquent to also save the user_id each time the polymorphic relationship is created?

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:

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]) . Remeber to have added user_id to your fillable array on the Comment model.

Else you can use

$comment = new Comment();
$comment->user_id =  auth()->user->id;
$comment->save()
etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM