How to use DB::raw in laravel
This article mainly introduces the relevant knowledge of how to use DB::raw in laravel, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this article on how to use DB::raw in laravel. Let's take a look at it.
In laravel, the "DB::raw ()" method is used for complex sql queries, which treat the result set as a temporary table and then use laravel's query constructor syntax for paging, with the syntax "DB::raw ('function or field');".
This article operating environment: Windows10 system, Laravel6 version, Dell G3 computer.
What is the use of DB::raw in laravel
Encountered a problem in the project, complex sql query, using laravel query constructor, very inconvenient, various query conditions splicing a long list of brain pain; then want to use the native sql statement to query, and then can not use laravel's paginate () paging method; this time DB::raw () method will come in handy! The principle of syntax is to treat the result set of your query as a temporary table, and then page it using laravel's query constructor syntax.
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 ("name, surname, (CASE WHEN (gender = 1) THEN' M'ELSE 'F'END) as gender_text"); this is the end of the article on "how DB::raw is used in laravel". Thank you for reading! I believe you all have a certain understanding of the knowledge of "how to use DB::raw in laravel". If you want to learn more, you are welcome to follow the industry information channel.