2017-03-22 8 views
0

Laravelで多対多の多型関係を定義する方法についてはチュートリアル*を読んでいますが、この関係でレコードを保存する方法は示されていません。Laravelでポリモーフィックな関係で保存するにはどうすればいいですか?

$tag = Tag::find(1); 
$video = Video::find(1); 
$tag->videos()->associate($video); 

or 

$tag->videos()->sync($video); 
:私はさまざまな方法で保存しようとしましたが、私には最も理にかなっての試みであり、彼らは

class Post extends Model 
{ 
    /** 
    * Get all of the tags for the post. 
    */ 
    public function tags() 
    { 
     return $this->morphToMany('App\Tag', 'taggable'); 
    } 
} 

class Tag extends Model 
{ 
    /** 
    * Get all of the posts that are assigned this tag. 
    */ 
    public function posts() 
    { 
     return $this->morphedByMany('App\Post', 'taggable'); 
    } 

    /** 
    * Get all of the videos that are assigned this tag. 
    */ 
    public function videos() 
    { 
     return $this->morphedByMany('App\Video', 'taggable'); 
    } 
} 

を持っている彼らの例では

これらのどれも動作していません。誰でも私に何を試すことができるかの手がかりを与えることができますか?

+0

エラーは何ですか? – apokryfos

答えて

2

それはそのように簡単です、thisセクションを参照してください。代わりに、手動での動画の属性を設定するので

、あなたは関係者の保存方法から直接コメントを挿入することがあります。

//Create a new Tag instance (fill the array with your own database fields) 
$tag = new Tag(['name' => 'Foo bar.']); 

//Find the video to insert into a tag 
$video = Video::find(1); 

//In the tag relationship, save a new video 
$tag->videos()->save($video); 
+0

それがうまくいかない場合は、あなたの投稿を編集し、あなたの関係を説明してください –

+1

ありがとうございます。それはそれを修正した。私はとても近かった。 – Dubby

関連する問題