这可能不是最佳答案,但您可以使用单一表单传递给控制器,然后将数据传递给多个存储库。
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']);
有关更多信息,请参阅文档:
https://laravel.com/docs/5.3/eloquent#inserts
如果您想将student id 传递给hobby,最简单的方法是从StudentRepository 返回学生并将其传递给HobbyRepository。
例如:
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。
这可能会解决您的扩展问题。