打印 laravel 模型查询产品的 SQL

1.在路由閉包打印sql

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

Route::get('/get-sql', function() {
DB::enableQueryLog();
$data = App\Models\BusinessProduct::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 App\Models;

use Illuminate\Database\Eloquent\Model;

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 App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Models\BusinessProduct; 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
}
]
上一篇:HDU 5690 All X 暴力循环节


下一篇:利用免费的Spire.XLS控件制作Excel报表