zoukankan      html  css  js  c++  java
  • 打印 laravel 模型查询产品的 SQL

    1.在路由閉包打印sql

    打印一段代码生产的 sql 语句,使用路由闭包做个实验

    Route::get('/get-sql', function() {
        DB::enableQueryLog();
        $data = AppModelsBusinessProduct::Enable(1)->get();
        return response()->json(DB::getQueryLog());
    });

    在浏览器打开:http://127.0.0.1:8000/get-sql

    [
        {
            "query":"select * from `fook_business_product` where `enable` = ?",
            "bindings":[
                1
            ],
            "time":13.02
        }
    ]

    2.在controller打印sql

    2.1定義路由

    Route::group(['prefix' => 'admin'], function () {
        $namespacePrefix="\App\Http\Controllers\Admin\";
        Route::get('/product',['uses' => $namespacePrefix . 'BusinessProductController@index', 'as' => 'index']);
    });

    2.2定時model

    <?php
    
    namespace AppModels;
    
    use IlluminateDatabaseEloquentModel;
    
    class BusinessProduct extends Model
    {
        protected $table = 'fook_business_product';
    
        /**
         * 是否有效(1、有效,0、無效  )
         * @author jackie <2019.01.23>
         */
        public function scopeEnable($query,$enable)
        {
            return $query->where('enable',$enable);
        }
    
    }

    2.3定義controller

    <?php
    
    namespace AppHttpControllersAdmin;
    
    use IlluminateHttpRequest;
    use AppHttpControllersController;
    use IlluminateSupportFacadesDB;
    use AppModelsBusinessProduct;
    
    class BusinessProductController extends Controller
    {
        public function index()
        {
            DB::enableQueryLog();
                $data = BusinessProduct::Enable(1)->first();
            return response()->json(DB::getQueryLog());
    
        }
    }

    2.4在瀏覽器打開:http://127.0.0.1:8000/admin/product

          
    [
        {
            "query":"select * from `fook_business_product` where `enable` = ? limit 1",
            "bindings":[
                1
            ],
            "time":12.42
        }
    ]
  • 相关阅读:
    Java
    Spring
    Q&A
    Q&A
    Q&A
    Spring
    Elasticsearch部署及基本概念
    rust(二) 变量及类型
    rust(一) 一些命令
    vim笔记
  • 原文地址:https://www.cnblogs.com/clubs/p/10307706.html
Copyright © 2011-2022 走看看