简体   繁体   English

如何在Laravel中保存数据库操作

[英]How to save database operation in laravel

Thanks for watching my first question. 感谢您收看我的第一个问题。
I have something confused. 我有些困惑。
How could I write the operations of database into database and don't write the function in every Controller? 如何将数据库的操作写入数据库,而不是在每个Controller中都编写函数?
I have considered middleware and find that must change my route register style. 我考虑过中间件,发现它必须更改我的路由寄存器样式。
my Route is this: 我的路线是这样的:

Route:resource('province','\\Modules\\Info\\Controllers\\P_ProvinceController');

Dose it has some awesome methods replace this? 剂量它有一些很棒的方法可以代替吗?

 public function Store(Request $request)
        {
            $params = $request->input('data');
            $params['CreateID'] = Auth::user()->id;
            $params['CreateName'] = Auth::user()->name;
            $params['CreateTime'] = Carbon::now();
            $province = P_ProvinceModel::Create($params);
            $params['Pro_Is_Del'] = 1;
            $log_info['table'] = $province->getTable();
            $log_info['type']  = "create";
            $log_info['user']  = Auth::user()->name;
            $log_info['datetime'] =  Carbon::now();
            LogModel::create($log_info);
            if($province){
                return response()->json(array(
                    'status' => 200,
                    'msg' => '新增成功',
                    'data' => $province
                ));
            }else
                return response()->json(array(
                    'status' => 500,
                    'msg' => '保存失败',
                ));

        }

Thanks. 谢谢。

Here is how I solved across model functionality 这是我跨模型功能解决的方法

First Create a Trait that does what you want on save. 首先创建一个可以保存所需内容的特征。

<?php

namespace App\Models\Observers;

trait CreatedByObserver
{
    public static function bootCreatedByObserver(){
        /** Simply means that whenever this model is creating a model do: */
        static::creating(function($model){
            if(auth()->check()){
                 $responsiblePerson = auth()->user()->first_name . " " . auth()->user()->last_name;
            } else {
                 $responsiblePerson = "system";
            }
            /** You can set any model variables within */
            $model->created_by = $responsiblePerson;
        });
    }
}

In there do all you need to do when a record is saved/created/updated/deleted 保存/创建/更新/删除记录时,您需要做的所有事情

Then In all Models you want this behaviour used add the trait. 然后在所有要使用此行为的模型中添加特征。

Check them out here : https://laravel.com/docs/5.2/eloquent#events 在这里查看它们: https : //laravel.com/docs/5.2/eloquent#events

As far i understand your question, you are asking for way to make your controller an abstract type, ie controller just need to handle the route and view not any other things(like database,application logic etc) which is the philosophy of the laravel Framework. 据我了解您的问题,您正在寻找使控制器成为抽象类型的方法,即控制器只需要处理路由并查看其他任何事物(如数据库,应用程序逻辑等),这就是laravel框架的理念。

To make your controller abstract (meaning of abstract as explained aboave), first you need to understand, "What your application logic are and what your database logic are ?" 要使您的控制器抽象(如前所述,抽象的含义),首先需要了解“应用逻辑是什么,数据库逻辑是什么?” when you understand these two things then, you can easily separate your aapplication logic and databasse logic from your controller. 当您了解了这两件事之后,就可以轻松地将应用程序逻辑和数据库逻辑从控制器中分离出来。

For example : For keeping your Application logic you can make service folder in your root of your project also you can make folder name 'Dao' (Database access object) in the same path of service . 例如:为了保持您的应用程序逻辑,您可以在项目的根目录中创建service文件夹,也可以在同一service路径中创建文件夹名称“ Dao”(数据库访问对象)。 You need to keep these folder in autoload from your composer. 您需要将这些文件夹保留在从作曲家自动加载的位置。 Just make class for service and your Dao. 只需为服务和您的Dao上课。

And now your application follow will be, First Route, will hit controller then controller will need to call some method in service and then service will call the respective DAO . 现在您的应用程序将是First Route,它将命中控制器,然后控制器将需要在service调用某些方法,然后服务将调用相应的DAO method. 方法。

Example : 范例:

Controller/YourController.php Controller / YourController.php

Class YourController extends Controller {

 public function Store(Request $request,yourservice,$yourService)
        {
        $this->myservice = $yourservice;
        $this->myservice->store('your inputs request');
return $something ;
}


}

service/yourService.php service / yourService.php

    Class yourService {

    public function store($yourinputs,yourDao $mydao){

     $this->mydao = $mydao;

//you can use your application logic here 
    return $this->mydao->create($yourinputs);
    }

And now the turn is for DAO : 现在轮到DAO

dao/yourdao.php dao / yourdao.php

use model // use your model here .
    class yourDao {
       public function create($yourdata,yourmodel $model){
       $this->model = $model;
      return $this->model->create($yourdata);

}
    }

Now, you can see the controller just save the data in database, but don't know how it is saving the data and what are the application logic. 现在,您可以看到控制器只是将数据保存在数据库中,但是不知道它如何保存数据以及应用程序的逻辑是什么。 This explanation is just a simple way of doing project to make a controller abstract. 这种解释只是做项目以使控制器抽象的一种简单方法。 There are other various ways of doing this. 还有其他多种方法可以执行此操作。 For example you can see Repository Design Pattern , which also used by laravel core . 例如,您可以看到laravel core也使用的Repository Design Pattern

Hope this explanation will not bore anyone . 希望这种解释不会让任何人感到厌烦。 :) Happy coding . :)编码愉快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM