Teach you how to easily output complete SQL statements in Laravel
Jul 17, 2020 pm 01:18 PM下面由Laravel教程欄目給大家介紹Laravel中輕松容易的輸出完整的SQL語句的方法,希望對(duì)需要的朋友有所幫助!
laravel 中自帶的查詢構(gòu)建方法
toSql
得到的 sql 語句并未綁定條件參數(shù),類似于這樣select * from
userswhere
id= ?
,所以寫了個(gè)擴(kuò)展包 laravel-dump-sql ,可以獲取完整的 sql 語句。
源碼
安裝
$ composer require guanguans/laravel-dump-sql -v
發(fā)布服務(wù)
$ php artisan vendor:publish --provider="Guanguans\\LaravelDumpSql\\ServiceProvider"
使用
安裝成功后查詢構(gòu)建器會(huì)新增
toRawSql
、dumpSql
、ddSql
三個(gè)方法
// 獲取 SQL User::where('id', 1)->toRawSql(); DB::table('user')->where('id', 1)->toRawSql(); // 打印 SQL User::where('id', 1)->dumpSql(); DB::table('user')->where('id', 1)->dumpSql(); // 打印 SQL 并退出 User::where('id', 1)->ddSql(); DB::table('user')->where('id', 1)->ddSql();
自定義方法名稱
發(fā)布配置文件
$ php artisan vendor:publish --tag=laravel-dump-sql
config/dumpsql.php
文件中配置方法名稱既可
<?php return [ /* * Get sql statement. */ 'to_raw_sql' => 'Your favorite method name', /* * Print SQL statements. */ 'dump_sql' => 'Your favorite method name', /* * Print SQL statements and exit. */ 'dd_sql' => 'Your favorite method name', ];
The above is the detailed content of Teach you how to easily output complete SQL statements in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

MySQL supports transaction processing, and uses the InnoDB storage engine to ensure data consistency and integrity. 1. Transactions are a set of SQL operations, either all succeed or all fail to roll back; 2. ACID attributes include atomicity, consistency, isolation and persistence; 3. The statements that manually control transactions are STARTTRANSACTION, COMMIT and ROLLBACK; 4. The four isolation levels include read not committed, read submitted, repeatable read and serialization; 5. Use transactions correctly to avoid long-term operation, turn off automatic commits, and reasonably handle locks and exceptions. Through these mechanisms, MySQL can achieve high reliability and concurrent control.

Character set and sorting rules issues are common when cross-platform migration or multi-person development, resulting in garbled code or inconsistent query. There are three core solutions: First, check and unify the character set of database, table, and fields to utf8mb4, view through SHOWCREATEDATABASE/TABLE, and modify it with ALTER statement; second, specify the utf8mb4 character set when the client connects, and set it in connection parameters or execute SETNAMES; third, select the sorting rules reasonably, and recommend using utf8mb4_unicode_ci to ensure the accuracy of comparison and sorting, and specify or modify it through ALTER when building the library and table.

To design a reliable MySQL backup solution, 1. First, clarify RTO and RPO indicators, and determine the backup frequency and method based on the acceptable downtime and data loss range of the business; 2. Adopt a hybrid backup strategy, combining logical backup (such as mysqldump), physical backup (such as PerconaXtraBackup) and binary log (binlog), to achieve rapid recovery and minimum data loss; 3. Test the recovery process regularly to ensure the effectiveness of the backup and be familiar with the recovery operations; 4. Pay attention to storage security, including off-site storage, encryption protection, version retention policy and backup task monitoring.

TooptimizecomplexJOINoperationsinMySQL,followfourkeysteps:1)EnsureproperindexingonbothsidesofJOINcolumns,especiallyusingcompositeindexesformulti-columnjoinsandavoidinglargeVARCHARindexes;2)ReducedataearlybyfilteringwithWHEREclausesandlimitingselected

The primary key is a field or combination that uniquely identifies records in a database table. Four principles must be followed when selecting: 1. Priority is given to using self-incremental integers such as INT or BIGINT to improve efficiency; 2. Avoid long strings such as UUID or mailboxes to avoid affecting performance; 3. Use business fields with caution, such as ID number due to poor stability; 4. Try not to use composite primary keys to maintain due to their complexity. At the same time, pay attention to the self-value-added configuration, delete the ID and do not recycle it, and do not manually insert the self-added field.

Laravel performance optimization can improve application efficiency through four core directions. 1. Use the cache mechanism to reduce duplicate queries, store infrequently changing data through Cache::remember() and other methods to reduce database access frequency; 2. Optimize database from the model to query statements, avoid N 1 queries, specifying field queries, adding indexes, paging processing and reading and writing separation, and reduce bottlenecks; 3. Use time-consuming operations such as email sending and file exporting to queue asynchronous processing, use Supervisor to manage workers and set up retry mechanisms; 4. Use middleware and service providers reasonably to avoid complex logic and unnecessary initialization code, and delay loading of services to improve startup efficiency.

CTEs are a feature introduced by MySQL8.0 to improve the readability and maintenance of complex queries. 1. CTE is a temporary result set, which is only valid in the current query, has a clear structure, and supports duplicate references; 2. Compared with subqueries, CTE is more readable, reusable and supports recursion; 3. Recursive CTE can process hierarchical data, such as organizational structure, which needs to include initial query and recursion parts; 4. Use suggestions include avoiding abuse, naming specifications, paying attention to performance and debugging methods.

A trigger is an automatically executed database object in MySQL that is used to perform predefined SQL operations when a specific event occurs. It can automatically update timestamps, verify or record data changes, maintain redundant fields, implement cascading operations, etc. To create a trigger, you need to specify the trigger timing (BEFORE/AFTER), event type (INSERT/UPDATE/DELETE) and execution logic, such as automatically populating the created_at field with BEFOREINSERT. When using it, you should pay attention to problems such as debugging difficulties, performance impact, high maintenance costs and inapplicability to distributed systems. It is recommended to keep the logic simple and make comments. Common scenarios include recording modification logs, restricting illegal operations, synchronous update of statistics tables and automatic filling
