2016-11-16 74 views
0

我正在使用Laravel 5.3,我試圖保存來自發布數據的1:多關係。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是我需要的,但我只是沒有跟着。

任何建議表示讚賞!

編輯

這裏就是我奮力最明白。

// 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

當你的對象爲空時,你得到錯誤Call to a member function activities() on null,在你的情況下,學生對象爲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