如何在雄辩中插入变形相关模型

S73*_*27B 1 laravel laravel-5

使用 laravel ducmunet 示例:

有像这样的表

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

And 3 model (post, command and video) .
Comment model has morphTo relation with post and video.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    /**
     * Get all of the owning commentable models.
     */
    public function commentable()
    {
        return $this->morphTo();
    }
}

class Post extends Model
{
    /**
     * Get all of the post's comments.
     */
    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
}

class Video extends Model
{
    /**
     * Get all of the video's comments.
     */
    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有解决方案将新记录插入与评论相关的模型(视频或帖子模型)。

例如,如果我有一个该工具的评论模型实例:

$nc = comment::find(3);
Run Code Online (Sandbox Code Playgroud)

现在我如何添加与 $nc 评论相关的新帖子或视频。

我无法使用保存方法,因为保存方法参数是帖子或视频模型的实例,但我不知道哪个模型与多态的 $nc 评论相关。


换句话说,我将在现有评论中添加新帖子或视频($nc)。

Bag*_*esa 5

您始终可以使用associate()and dissociate()just likeBelongsTo关系。例如:

$video = Video::find(1);
$comment = new Comment();
$comment->commentable()->associate($video);
$comment->save()
Run Code Online (Sandbox Code Playgroud)

请注意,一条评论属于单个视频或帖子。快乐编码!


Mar*_*eca 5

使用 Associate() 的正确使用方法改进 Bagus 答案

$video = Video::find(1)

$comment = new Comment();
$comment->commentable()->associate($video);
$comment->save();
Run Code Online (Sandbox Code Playgroud)