laravel

时间:2017-02-15 03:46:53

标签: database forms laravel controller models

所以我的数据库中有2个表:示例学生和爱好。 所以这意味着2个控制器以及StudentController和HobbyController。 以及2个模型。

我有一个表格,例如:

  • 1.student name

  • 2.年龄

  • 3.height

  • 4.weight

  • 5.bmi

  • 6.hobby

  • 7.schedule

  • 8.intensity

  • 9.diet
前五个必须去学生控制器 和6-9去爱好控制器.. 我这样做有多么糟糕?我不想要两种不同的形式......

1 个答案:

答案 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']);

有关更多信息,请参阅文档:

  

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

这可能会解决您的扩展问题。