$query=\DB::table('users')->where('id',10);$sql=str_replace_array('?',$query->getBindings(),$query->toSql());dd($sql); 生成的SQL语句,使用问号作为位置参数,如果想要格式化输出,还可以使用 vsprintf 这个函数:
\DB::connection()->enableQueryLog(); some sql action... $query=\DB::getQueryLog(); $lastQuery=end($query); dd($lastQuery); php artisan tinker DB::listen(function($sql){ var_dump($sql); }); InsideAppServiceProvider.phpadd the following to the boot method: useDB;useEvent;//..p...
DB::connection()->enableQueryLog();//SQL语句$queries=DB::getQueryLog(); $query=end($queries); print_r($query);
使用enableQueryLog()函数打开SQL记录,然后是正常的数据库逻辑,最后,使用 getQueryLog() 方法获取一个包含了生成的SQL语句,还有绑定的参数。 上述语句打印的结果大致如下:还有一种方法,就是链式调用 QueryBuilder 的 toSql 方法,即可打印当前模型的SQL语句,而并不执行。
在Laravel的控制器内部编写普通SQL查询,可以通过使用Laravel提供的数据库查询构建器(Query Builder)或原生SQL语句的方式来实现。 使用数据库查询构建器: Laravel的数据库查询构建器提供了一种更简洁、安全的方式来执行数据库查询操作。以下是在Laravel控制器内部编写普通SQL查询的步骤:...
getQuery() 获取完整的 SQL 语句 mergeBindings() 将binding 参数合并到查询中 自带闭包 User::whereIn('id', function($query){ $query->select('user_id') ->from('admin_user') ->whereIn('type', ['1', '2']); })->get(); 获得的 SQL 如下: SELECT * FROM `user` where `id` IN ( ...
通过查看源码我们知道all方法,其实是调用了 get 方法并默认返回所有字段。 我们为这个查询添加条件,一遍精简输出内容:$vipContacts = Contact::where('vip', true)->get();筛选出所有vip的合约。eloquent门面为我们提供了很多好用的链式操作方法, 在query builder筛选出合适的条目后,返回一个eloquent collection,...
dumpListenedSql() - 打印被监听到的 sql User::query()->where('id',1)->dumpListenedSql()->first(); User::query()->where('id',2)->first(); [Laravel] [39.97ms]select*from`xb_users`where`id`='1'limit 1|GET: / [Laravel] [39.93ms]select*from`xb_users`where`id`='2'limit 1|...
If you would like to customize the query executed by the validation rule, you may use the Rule class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the | character to delimit them:...
1DB::table('users') 2 ->whereExists(function($query) 3 { 4 $query->select(DB::raw(1)) 5 ->from('orders') 6 ->whereRaw('orders.user_id = users.id'); 7 }) 8 ->get();The query above will produce the following SQL: