首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用laravel控制2个控制器的一种形式

用laravel控制2个控制器的一种形式
EN

Stack Overflow用户
提问于 2017-02-15 03:46:52
回答 1查看 1.2K关注 0票数 0

因此,我的数据库中有两个表:示例、学生和业余爱好。因此,这意味着两个控制器以及StudentController和HobbyController。还有两个模型。

我有一个表格,例如:

  • 1.学生姓名
  • 2.age
  • 3.height
  • 4.weight
  • 5.bmi
  • 6.hobby
  • 7.schedule
  • 8.intensity
  • 9.diet

前五个必须交给学生管理员,6-9必须交给学生管理员。我该怎么做?我不想要两种不同的形式..。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-15 04:21:07

这可能不是最好的答案,但您可以使用单个表单传递给控制器,然后将数据传递给多个存储库。

route.php

代码语言:javascript
运行
复制
Route::resource('student', 'StudentController');

StudentController.php

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
public function store($data)
{
   // your implementation on storing the user.
}

HobbyRepository.php

代码语言:javascript
运行
复制
public function store($data)
{
   // your implementation on storing the hobby.
}

您可以使用任何方法和变量从控制器传递数据。希望这能有所帮助。

编辑:

关于存储和检索信息的扩展问题。

如文件中所述:

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
$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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42240354

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档