因此,我的数据库中有两个表:示例、学生和业余爱好。因此,这意味着两个控制器以及StudentController和HobbyController。还有两个模型。
我有一个表格,例如:
前五个必须交给学生管理员,6-9必须交给学生管理员。我该怎么做?我不想要两种不同的形式..。
发布于 2017-02-15 04:21:07
这可能不是最好的答案,但您可以使用单个表单传递给控制器,然后将数据传递给多个存储库。
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
。
例如:
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
。
这可能会解决你的扩展问题。
https://stackoverflow.com/questions/42240354
复制相似问题