我正在使用Laravel 5.3,我正在尝试保存从帖子数据中获得的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 :(得分:0)
当对象为null时,您会收到错误Call to a member function activities() on null
,在您的情况下,学生对象为null。放置if语句,如:
调用null
上的成员函数activities()$student = Student::find($request->id);
if($student){
foreach ($request->activities as $activity) {
$student->activities()->save([
'student_id' => $request->id,
'activity_id' => $activity,
]);
}
}