2016-12-05 71 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() 

只是一個提醒,一個評論屬於單個視頻或交。快樂的編碼!