当先锋百科网

首页 1 2 3 4 5 6 7

这个简单的文章演示了Laravel 8中获取上次执行的SQL语句。将使用toSql(),DB ::enableQueryLog()和DB ::getQueryLog()在laravel 8中打印最后一个SQL查询。

因此,让我们看看下面的示例,并根据需要使用它们。

示例1:

控制器代码:

<?php
  
namespace App\Http\Controllers;
  
use App\Models\User;
  
class UserController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToGoogle()
    {
        $query = User::select("*")->toSql();
            
        dd($query);
    }
}

输出:

select * from `users`

示例2:

控制器代码:

<?php
  
namespace App\Http\Controllers;
   
use App\Models\User;
use DB;
    
class UserController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToGoogle()
    {
        DB::enableQueryLog();
  
        $users = User::select("*")->get();
        $quries = DB::getQueryLog();
  
        dd($quries);
    }
}

输出:

array:1 [▼
  0 => array:3 [▼
    "query" => "select * from `users`"
    "bindings" => []
    "time" => 4.25
  ]
]

示例3:

控制器代码:

<?php
  
namespace App\Http\Controllers;
   
use App\Models\User;
use DB;
    
class UserController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToGoogle()
    {
        DB::enableQueryLog();
            
        $users = User::select("*")->get();
        $query = DB::getQueryLog();
  
        $query = end($query);
  
        dd($query);
    }
}

输出:

array:3 [▼
  "query" => "select * from `users`"
  "bindings" => []
  "time" => 2.07
]

https://www.learnfk.com/article-how-to-get-last-executed-query-in-laravel-8example