【问题标题】:should i put this code in the model or controller in laravel我应该将此代码放在 laravel 的模型或控制器中吗
【发布时间】:2020-03-15 12:08:51
【问题描述】:

好的,所以我正在提高我的 Laravel 和 MVC 技能..目前所有这些都在控制器中(我知道这很糟糕,这就是我在这里的原因,我正在努力做得更好:D)

从 UI 接收数据作为帖子(完成) 我必须存储一个文件(完成) 将该文件 ID 和路径存储在文件表中(完成) 使用查询生成器创建新记录并使用上述记录 ID(完成)

但是我应该把它保存在控制器中还是属于模型,特别是获取文件和存储记录等。

我是否在控制器中构建它并使用 save()? 或从文件的新模型返回并在返回时通过(我觉得这是最好的方式)。

文件模型(待建)

保存文件从文件表返回文件ID

商业模式保存业务数据

控制器文件: 使用 /app/fileModel

$fileStored = 调用文件模型并传递请求->文件 用于存储

$businessFile = $fileStored;

保存()

我想我已经回答了自己的问题,但我只是确定一下。

我以反模式编码而闻名,所以我要求一些指导而不是代码谢谢

另外,如果有人知道一个只讨论 laravel 东西的地方,所以不要放在这里,我希望能进行一次愉快的交谈,我的一些问题可能看起来很愚蠢,我有时只需要一个音板。

【问题讨论】:

  • 常见的做法是使用 ViewModel。如果您使用的是 MVC,那么您已经有一个模型。在视图模型的基础上构建以获得您需要的一切。你仍然需要在控制器中保存,除非你使用存储过程来完成这项工作。

标签: laravel model-view-controller eloquent model


【解决方案1】:

好的,这是我的解决方案。

   public function create(Request $request)
    {

//get files from request
        $Match1 = $request->file('Match1')->store('media/scores');
        $Match2 = $request->file('Match2')->store('media/scores');
        $Match3 = $request->file('Match3')->store('media/scores');
//build collection array to loop through saving them 
        $collection = collect([$Match1,$Match2,$Match3]);
// store return paths in to new array
        $mediapaths = array();
//loop through collections saving details in to files table pushing to the paths array
        foreach($collection as $MatchScore) {
          $ScoresSaved = Files::create([
            'user_id' => $request->userID,
             'file_name' => $request->title,
             'type' => 'png',
             'category_id'=>3,
             'path' => $MatchScore,
             'is_public'=>0
         ]);
        array_push($mediapaths, $ScoresSaved);
       }

//Save the score with new media path to the model
       $scores = new Scores;
       $scores->tournament=22; 
       $scores->round='Finals'; 
       $scores->homeArcade=2578; 
       $scores->homePlayer=2; 
       $scores->opponenet=2; 
       $scores->Match1=$mediapaths[0]['id'];
       $scores->Match2=$mediapaths[1]['id']; 
       $scores->Match3=$mediapaths[2]['id']; 
       $scores->Match1Score=22; 
       $scores->Match2Score=44; 
       $scores->Match3Score=88; 
       $scores->comments='testing full flow'; 
       $scores->winner=2; 
       $scores->referee=3; 
       $scores->confirmed=1; 
       $scores->dispute=0; 
       $scores->submitedBy=2;
       $scores->save();

       return response()->json([
        'result' => 'Success'
    ]);

   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-22
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多