這可能不是最好的答案,但您可以使用單一形式傳遞給控制器,然後將數據傳遞給多個存儲庫。
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
。
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
。
這可能會解決您的擴展問題。
您可以使用重定向到[action](https://laravel.com/docs/5.4/responses#redirecting-controller-actions)方法,或者您可以將該邏輯提取到服務 – jarguez01
thx以獲得建議...正在進行提取到服務 – Mikethetechy