所以我的数据库中有2个表:示例学生和爱好。 所以这意味着2个控制器以及StudentController和HobbyController。 以及2个模型。
我有一个表格,例如:
1.student name
2.年龄
3.height
4.weight
5.bmi
6.hobby
7.schedule
8.intensity
答案 0 :(得分:0)
这可能不是最佳答案,但您可以使用单一表单传递给控制器,然后将数据传递给多个存储库。
<强> route.php 强>
Route::resource('student', 'StudentController');
<强> StudentController.php 强>
public function __constructor(StudentRepository $student, HobbyRepository $hobby)
{
$this->student = $student;
$this->hobby= $hobby;
}
public function store(Request $request)
{
$data = $request->all();
$hobby = [
'hobby' => $data['hobby'],
'schedule' => $data['schedule'],
'intensity' => $data['intensity'],
'diet' => $data['diet'],
];
$student = [
'student_name' => $data['student_name'],
'age' => $data['age'],
'height' => $data['height'],
'weight' => $data['weight'],
'bmi' => $data['bmi'],
];
$this->student->store($student);
$this->hobby->store($hobby);
//your other codes.
}
<强> StudentRepository.php 强>
public function store($data)
{
// your implementation on storing the user.
}
<强> HobbyRepository.php 强>
public function store($data)
{
// your implementation on storing the hobby.
}
您可以使用任何方法和变量从控制器传递数据。希望这会有所帮助。
编辑:
关于存储和检索信息的扩展问题。
正如文档中所述:
The create method returns the saved model instance:
$flight = App\Flight::create(['name' => 'Flight 10']);
有关更多信息,请参阅文档:
如果您想将student id
传递给hobby
,最简单的方法是从StudentRepository
返回学生并将其传递给HobbyRepository
。
E.g:
<强> StudentRepository.php 强>
public function store($data)
{
// your implementation on storing the user.
$student = [] // array of the student informations to be stored.
return Student::create($student); //you will have student information here.
}
<强> StudentController.php 强>
$student = $this->student->store($student); //store the student information and get the student instance.
$this->hobby->store($hobby, $student->id); //pass it to the hobby to store id.
您应该更改hobbyRepository
商店以使用student id
。
这可能会解决您的扩展问题。