2016-12-05 41 views
0

变身相关模型使用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'); 
    } 
} 

是否有插入新记录溶液注入到相关的评论模式(视频或后期模型)。

例如,如果我有意见模型的instace本仪器:

$nc = comment::find(3); 

现在,我怎么添加与$ NC评论新文章或视频。

我不能使用save方法,因为save方法参数是一个post或video模型的实例,但是我不知道哪个模型与$ nc有关的多态性有关。


换句话说,我会添加一个新的帖子或视频到现有​​评论($ nc)。

+0

因此,要确认的事情,你想关联一个视频或张贴评论? –

+0

@ bagus-tesa是的。在帖子或视频表格中创建的新视频或帖子记录属于$ nc Comment。换句话说,我会添加新的帖子或视频到现有​​的评论($ nc) – S7327B

+0

我认为有轻微的沟通不畅,我认为这是一个视频/帖子有很多评论(应该已经在我的回答中回答)。但你的答案看起来像一个评论可以有几个视频/文章。如果这是真的,你的关系有点不匹配......等一下。 –

回答

0

您可以随时使用associate()dissociate(),就像BelongsTo关系一样。例如:

$video = Video::find(1); 
$comment = new Comment(); 
$comment->associate($video); 
$comment->save() 

只是一个提醒,一个评论属于单个视频或交。快乐的编码!