2016-11-16 8 views
0

私はLaravel 5.3を使用していると私は1保存しようとしています:POSTデータから来ている多くの関係。Laravel 1:多くの関係を保存するにはどうすればよいですか?

私は関係がセットアップされていると私はオブジェクトを読み取るときには、正しく動作しているが、私は実際にそれらを保存する方法を考え出したていません。 (これまでのハードコーディング)。

... 
$data = new Student; 
$data->fill($request->all()); 

$student = Student::find($request->id); // get the id of the newly created student 

foreach ($request->activities as $activity) { 
    $student->activities()->save([ 
     'student_id' => $request->id, 
     'activity_id' => $activity, 
    ]); 
} 

私は取得していますエラーは次のとおりです。

Call to a member function activities() on null 

activitiesは配列として私のポストデータに全体で来ています。

activities[ 
    [0] => 1 
    [0] => 2 
    ... 
] 

The value(s) of each key are the id's of the activity. 

活動

public function students() 
{ 
    return $this->belongsToMany('App\Student'); 
} 

学生

public function activities() 
{ 
    return $this->belongsToMany('App\Activity'); 
} 

私はactivity_studentと呼ばれる表にこの関係を保存しようとしています。

私はthis part from the docsは、私は必要なものだと思うが、私はちょうどに沿って、以下のいませんよ。

任意の提案は大歓迎です!私が理解することが最も苦労していますのはここ

EDIT

です。

// Save things like first_name, last_name into students table 
$student->fill($request->all()); 

if ($student->save()) { 

    // grab the student's activities and insert into the activity_student table. 
    // $activities is an array that only contains the id of the activity 
     $student->activities()->sync($activities); 
} 

だから私はactivitiesテーブル、studentsテーブル、およびactivity_studentテーブルを持っています。モデルは上です...私はこの時点でサークルに入っています。 :(

あなたの助けのためにどうもありがとうございます!

ソリューション

はそんなに@Jamalありがとうございます!ここで

は私がなってしまったものです。

... 
if ($data->save()) { 
    $student = Student::find($request->id); 
    $student->activities()->attach($activities); 
} 

... 

答えて

0

あなたのオブジェクトがnullの場合、エラーCall to a member function activities() on nullが返されます。あなたのケースでは、studentオブジェクトがnullです。 E:ヌル

$student = Student::find($request->id); 
if($student){ 
foreach ($request->activities as $activity) { 
    $student->activities()->save([ 
     'student_id' => $request->id, 
     'activity_id' => $activity, 
    ]); 
} 
} 
+0

上のメンバ関数活動に

()の呼び出しは、あなたの答えをありがとうございました!私は何らかの理由で本当に苦労しています。私は 'sync'メソッドも調べました。私はピボットテーブルにモデルを保存することで頭を抱えているようには思えません。うまくいけば私の固執をよりよく示すために私の質問を更新しました。 – Damon

+1

@Damonのように多対多をしています。このセクションに従ってくださいhttps://laravel.com/docs/5.3/eloquent-relationships#updating-many-to-many-relationships –

+0

私はあなたのコメントをキャッチしなかった - 私はそれを見ていきます。ありがとうございました! – Damon

関連する問題