Home > PHP Framework > Laravel > body text

What is the usage of DB::raw in laravel?

WBOY
Release: 2022-02-18 11:17:27
Original
5097 people have browsed it

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');".

What is the usage of DB::raw in laravel?

#The operating environment of this article: Windows 10 system, Laravel version 6, Dell G3 computer.

What is the usage of DB::raw in laravel

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(&#39;status&#39;, &#39;<>&#39;, 1)
                   ->groupBy(&#39;status&#39;)
                   ->get();
Copy after login

Example 2:

 DB::table(&#39;someTable&#39;)
->selectRaw(&#39;count(*), min(some_field) as someMin, max(another_field) as someMax&#39;)
->get();
Copy after login

Example 3:

DB::table(&#39;someTable&#39;)->select(
array(
        DB::raw(&#39;min(some_field) as someMin&#39;),
        DB::raw(&#39;max(another_field) as someMax&#39;),
        DB::raw(&#39;COUNT(*) as `count`&#39;)
    )
)->get()
Copy after login

Example 4:

SELECT 
  (CASE WHEN (gender = 1) THEN &#39;M&#39; ELSE &#39;F&#39; END) AS gender_text 
  FROM users;
$users = DB::table(&#39;users&#39;)
  ->select(DB::raw("
  name,
  surname,  
  (CASE WHEN (gender = 1) THEN &#39;M&#39; ELSE &#39;F&#39; END) as gender_text")
);
Copy after login

[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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!