2016-05-17 10 views
0

私はこのようなレッスンモデルがあります:挿入デフォルト値

class Lesson extends Model 
    { 
     use SoftDeletes; 

     public $primaryKey = 'lesson_id'; 
     . 
     . 
     . 

     public function contents() 
     { 
       return $this->hasMany('App\Content', 'lesson_id', 'lesson_id'); 
     } 

    } 

を、他方でコンテンツモデルのようなものです:

class Content extends Model 
{ 
    public $primaryKey = 'content_id'; 
    public $timestamps = false; 

    public function lesson() 
    { 
     return $this->belongsTo('App\Lesson', 'lesson_id', 'lesson_id'); 
    } 

} 

として、あなたが参照してくださいhasMany 2モデル間の関係です。

コンテンツモデルは、この属性ました:

content_id 
lesson_id 
contentable_id 
contentable_type 
order 

とレッスンモデルは、これらがあります

lesson_id 
title 
content 

今、私は具体的な授業の内容を保存する際、一部のコンテンツが自動的に属性がレッスンに基づいて埋めることがしたいですモデル属性。選択授業の例lesson_idため

$lesson = Lesson::findOrFail($lessonID); 
$lesson->contents()->create(
     [ 
      'contentable_id' => $newUnit['unit_id'], 
     ] 
); 

は、コンテンツモデルのlesson_idcontentable_typeなどApp\Lesson文字列として保存します。

どうすればいいですか?

答えて

0

、それを試してみてくださいそして、

レッスンモデル

class Lesson extends Model 
    { 
     use SoftDeletes; 

     public $primaryKey = 'lesson_id'; 
     . 
     . 
     . 

     public function contents() 
     { 
       return $this->hasMany('App\Content', 'content'); 
     } 

    } 

コンテンツモデル

class Content extends Model 
{ 
    public $primaryKey = 'content_id'; 
    public $timestamps = false; 

    public function lesson() 
    { 
     return $this->belongsTo('App\Lesson', 'content'); 
    } 

} 

以下の変更を行います

$lesson = Lesson::findOrFail($lessonID); $content = new Content(); $content->contentable_id = '1111'; $lesson->contents()->save(content); 
+0

レッスンモデルの 'content'フィールドは簡単なTEXTフィールドであり、レッスンモデルのコンテンツモデルの外部キーではありません –

+0

私のコードをチェックしましたか? –

+0

'$ this-> hasMany( 'App \ Content'、 'content');と' $ this-> belongsTo( 'App \ Lesson'、 'content'); 'に' content'フィールドを追加しました。それは正しくありません。 'lesson'モデルの' lesson_id'で 'contentable_id'を自動的に埋めたいと思っています。手動で初期化します。 –