douling6469 2019-03-18 03:02
浏览 245
已采纳

在一个控制器中使用2个模型是不好的做法

We are using Laravel and we have multiple models controllers.

Ex:

Model1 and Model2 and they corresponding controllers Controller1 and Controller2. We need to make a new entry for Model2 every time we create new entry for Model1.

The question is, is it bad practice to make new entries in Model1 and Model2 in Controller1

public function store(Request $request)
{
    //Create new Model1
    $model1 = new Model1;
    $model1->bla = "Model1";
    $model1->save();

    //Create new Model2
    $model2 = new Model2;
    $model2->bla = "Model2";
    $model2->save();
}
  • 写回答

2条回答 默认 最新

  • dongzhang6677 2019-03-18 03:43
    关注

    I have multiple projects that are doing what you just have said, saving entries on a multiple tables at once. I believe that this is really happening on an app in a real world scenario.

    Here's what I am doing though:

    public function store(Request $request)
    {
        $main = $this->saveModel1($request);
        $this->saveModel2($request);    
    
        return redirect()->route('my.route.name.for.edit', $main->id);
    }
    
    private function saveModel1($request)
    {
        $model1 = new Model1;
        $model1->bla = "Model1";
        $model1->save();
        return $model1->id;
    }
    
    private function saveModel2($request)
    {
        $model2 = new Model2;
        $model2->bla = "Model2";
        $model2->save();
    }
    

    UPDATE: This answer has been selected as correct, but I just want to add that on condition like this, it is safe to enclose your saving query into a transaction.

    DB::beginTransaction();
    try
    {
    
    }
    catch (\PDOException $e)
    {
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog