Home >PHP Framework >Laravel >What is the usage of DB::raw in laravel?
In laravel, the "DB::raw()" method is used for complex sql queries. This method can treat the queried result set as a temporary table, and then use laravel's query builder syntax for paging Processing, the syntax is "DB::raw('function or field');".
#The operating environment of this article: Windows 10 system, Laravel version 6, Dell G3 computer.
I encountered a problem in the project, complex sql query, using laravel's query constructor is very inconvenient, various queries Splicing a long list of conditions makes my head hurt; then I want to use native SQL statements to query, and then I can’t use laravel’s paginate() paging method; this is when the DB::raw() method comes in handy! The principle of the syntax is to treat the result set of your query as a temporary table, and then use laravel's query builder syntax for paging processing;
Example 1:
$users = DB::table('users') ->select(DB::raw('count(*) as user_count, status')) ->where('status', '<>', 1) ->groupBy('status') ->get();
Example 2:
DB::table('someTable') ->selectRaw('count(*), min(some_field) as someMin, max(another_field) as someMax') ->get();
Example 3:
DB::table('someTable')->select( array( DB::raw('min(some_field) as someMin'), DB::raw('max(another_field) as someMax'), DB::raw('COUNT(*) as `count`') ) )->get()
Example 4:
SELECT (CASE WHEN (gender = 1) THEN 'M' ELSE 'F' END) AS gender_text FROM users; $users = DB::table('users') ->select(DB::raw(" name, surname, (CASE WHEN (gender = 1) THEN 'M' ELSE 'F' END) as gender_text") );
[Related recommendations: laravel video tutorial]
The above is the detailed content of What is the usage of DB::raw in laravel?. For more information, please follow other related articles on the PHP Chinese website!