[Laravel5.2 documentation] database -- Query Builder

Source: Internet
Author: User
[Laravel5.2 documentation] database -- Query Builder 1. Introduction

The database query builder provides a convenient and smooth interface for creating and running database queries. The query builder can be used to perform most database operations in an application and work on all supported database systems.

Note: The Laravel Query Builder uses the PDO parameter binding to prevent SQL injection attacks and does not need to filter the strings passed to the binding.

2. obtain the result setRetrieve all rows from a table

Before querying, use the table method of the DB facade. The table method returns a query builder for a given table, allowing you to link more constraints to the query and finally return the query result. In this example, we use the get method to retrieve all records in the table:

 Get (); return view ('user. Index', ['users' => $ users]);}

Like native queries, the get method returns an array of result sets. each result is an StdClass instance of the PHP object. You can access the value of a column like the attribute of an object:

foreach ($users as $user) {    echo $user->name;}
Retrieve a row/column from a table

If you only want to obtain a row of data from the data table, you can use the first method, which will return a single StdClass object:

$user = DB::table('users')->where('name', 'John')->first();echo $user->name;

If you do not need a complete row, you can use the value method to obtain a single value from the result. this method will directly return the value of the specified column:

$email = DB::table('users')->where('name', 'John')->value('email');
Obtain the block result set from a table.

If you need to process hundreds of thousands of database records, you can use the chunk method to obtain a small part of the result set at a time, and then fill each small piece of data into the closure to be processed, this method is useful when writing Artisan commands that process a large number of database records. For example, we can process all users tables into a group block that processes 100 records at a time:

DB::table('users')->chunk(100, function($users) {    foreach ($users as $user) {        //    }});

You can abort block execution by returning false from the closure function:

DB: table ('users')-> chunk (100, function ($ users) {// processing result set... return false ;});
Get the data column value list

If you want to obtain an array containing a single column value, you can use the lists method. In this example, we obtain the array of all titles:

$titles = DB::table('roles')->lists('title');foreach ($titles as $title) {    echo $title;}

You can also specify more custom keys for the column values in the returned array (this custom key must be another field column name of the table; otherwise, an error is reported ):

$roles = DB::table('roles')->lists('title', 'name');foreach ($roles as $name => $title) {    echo $title;}
Aggregate Functions

The queue builder also provides many aggregation methods, such as count, max, min, avg, and sum. you can call these methods after constructing a query:

$users = DB::table('users')->count();$price = DB::table('orders')->max('price');

Of course, you can join other query clauses and aggregate functions to build a query:

$price = DB::table('orders')                ->where('finalized', 1)                ->avg('price');
3. query (Select)Query clause

Of course, we do not always want to get all columns of the data table. Using the select method, you can specify a custom select clause for the query:

$users = DB::table('users')->select('name', 'email as user_email')->get();

The distinct method allows you to forcibly query returned result sets that are not repeated:

$users = DB::table('users')->distinct()->get();

If you already have a query builder instance and want to add a query column to an existing select clause, you can use the addSelect method:

$query = DB::table('users')->select('name');$users = $query->addSelect('age')->get();
Native expression

Sometimes you want to use native expressions in the query. these expressions will be injected into the query in the form of strings, so be careful not to be injected by SQL. To create a native expression, you can use the DB: raw method:

$users = DB::table('users')                     ->select(DB::raw('count(*) as user_count, status'))                     ->where('status', '<>', 1)                     ->groupBy('status')                     ->get();
4. Join)Internal connection (equivalent connection)

The query builder can also be used to compile basic SQL "internal connections". you can use the join method on the query builder instance, the first parameter passed to the join method is the name of the table you need to connect to, and the remaining parameters are the column constraints specified for the connection. of course, as you can see, you can join multiple tables in a single query:

$users = DB::table('users')            ->join('contacts', 'users.id', '=', 'contacts.user_id')            ->join('orders', 'users.id', '=', 'orders.user_id')            ->select('users.*', 'contacts.phone', 'orders.price')            ->get();
LEFT JOIN

If you want to execute "left join" instead of "inner join", you can use the leftJoin method. This method is the same as the join method:

$users = DB::table('users')            ->leftJoin('posts', 'users.id', '=', 'posts.user_id')            ->get();
Advanced connection statement

You can also specify more advanced join clauses and pass a closure to the join method as the 2nd parameter of the method. The closure will return the JoinClause object that allows you to specify the join clause constraints:

DB::table('users')        ->join('contacts', function ($join) {            $join->on('users.id', '=', 'contacts.user_id')->orOn(...);        })        ->get();

If you want to use a "where" clause in the connection, you can use the where and orWhere methods in the query. These methods compare the column and value, instead of comparing the column and column:

DB::table('users')        ->join('contacts', function ($join) {            $join->on('users.id', '=', 'contacts.user_id')                 ->where('contacts.user_id', '>', 5);        })        ->get();
5. Union)

The query builder also provides a "union" shortcut for two queries. for example, you need to create an independent query and then use the union method to combine it with the second query:

$first = DB::table('users')            ->whereNull('first_name');$users = DB::table('users')            ->whereNull('last_name')            ->union($first)            ->get();

The unionAll method is also valid and has the same usage as the union method.

6. Where clauseSimple where clause

You can add a where clause to the query by using the where method on the query builder. to call the where most basic method, three parameters are required. The first parameter is the column name, the second parameter is an arbitrary operator supported by the database system, and the third parameter is the value to be compared in this column.

For example, the following is a query that verifies that the value of the "votes" column is 100:

$users = DB::table('users')->where('votes', '=', 100)->get();

For convenience, if you simply compare whether the column value is equal to the given value, you can directly use the value as the second parameter of the where method:

$users = DB::table('users')->where('votes', 100)->get();

Of course, you can use other operators to compile the where clause:

$users = DB::table('users')                ->where('votes', '>=', 100)                ->get();$users = DB::table('users')                ->where('votes', '<>', 100)                ->get();$users = DB::table('users')                ->where('name', 'like', 'T%')                ->get();
Or

You can use the method chain to link multiple where constraints, or add the or clause to the query. the orWhere method and the where method receive the same parameters:

$users = DB::table('users')                    ->where('votes', '>', 100)                    ->orWhere('name', 'John')                    ->get();
More Where clauses

WhereBetween

The whereBetween method verifies whether the column value is between the given values:

$users = DB::table('users')                    ->whereBetween('votes', [1, 100])->get();

WhereNotBetween

The whereNotBetween method verifies that the column value is not between the given values:

$users = DB::table('users')                    ->whereNotBetween('votes', [1, 100])                    ->get();

WhereIn/whereNotIn

The whereIn method verifies whether the value of a given column is in a given array:

$users = DB::table('users')                    ->whereIn('id', [1, 2, 3])                    ->get();

The whereNotIn method verifies that the value of a given column is not in the given array:

$users = DB::table('users')                    ->whereNotIn('id', [1, 2, 3])                    ->get();

WhereNull/whereNotNull

The whereNull method verifies that the value of a given column is NULL:

$users = DB::table('users')                    ->whereNull('updated_at')                    ->get();

The whereNotNull method is used to verify that the value of a given column is not NULL:

$users = DB::table('users')                    ->whereNotNull('updated_at')                    ->get();
Advanced Where clause

Parameter group

Sometimes you need to create more advanced where clauses such as "where exists" or nested parameter groups. The Laravel query builder can also process this. Let's start with an example of grouping constraints in parentheses:

DB::table('users')            ->where('name', '=', 'John')            ->orWhere(function ($query) {                $query->where('votes', '>', 100)                      ->where('title', '<>', 'Admin');            })            ->get();

As you can see, the closure is passed to the orWhere method to construct the query builder to start a constraint group ,, this closure obtains an instance of the query builder used to set the constraints contained in the brackets. The preceding statement is equivalent to the following SQL statement:

select * from users where name = 'John' or (votes > 100 and title <> 'Admin')

Exists statement

The whereExists method allows you to write a where existSQL clause. the whereExists method receives a closure parameter, which obtains a query builder instance and allows you to define a query placed in the "exists" clause:

DB::table('users')            ->whereExists(function ($query) {                $query->select(DB::raw(1))                      ->from('orders')                      ->whereRaw('orders.user_id = users.id');            })            ->get();

The preceding query is equivalent to the following SQL statement:

select * from userswhere exists (    select 1 from orders where orders.user_id = users.id)
7. sorting, grouping, and limitationOrderBy

The orderBy method allows you to sort the result set by the given column. The first parameter of orderBy should be the column you want to sort, and the second parameter controls the direction of sorting-asc or desc:

$users = DB::table('users')                ->orderBy('name', 'desc')                ->get();
GroupBy/having/havingRaw

The groupBy and having methods are used to group result sets. the usage of the having method and the where method is similar:

$users = DB::table('users')                ->groupBy('account_id')                ->having('account_id', '>', 100)                ->get();

The havingRaw method can be used to set the native string as the value of the having clause. for example, we need to find all the parts with prices greater than $2500:

$users = DB::table('orders')                ->select('department', DB::raw('SUM(price) as total_sales'))                ->groupBy('department')                ->havingRaw('SUM(price) > 2500')                ->get();
Skip/take

To limit the number of returned result sets in a query, or skip the specified number of results in a query, you can use the skip and take methods:

$users = DB::table('users')->skip(10)->take(5)->get();
8. Insert)

The query builder also provides the insert method to insert records into the data table. The insert method is used to insert column names and values in the array format:

DB::table('users')->insert(    ['email' => 'john@example.com', 'votes' => 0]);

You can even insert multiple records by inputting multiple arrays at a time. each array indicates the records to be inserted into the data table:

DB::table('users')->insert([    ['email' => 'taylor@example.com', 'votes' => 0],    ['email' => 'dayle@example.com', 'votes' => 0]]);
Auto-increment ID

If the data table has an auto-increment ID, using the insertGetId method to insert records will return the ID value:

$id = DB::table('users')->insertGetId(    ['email' => 'john@example.com', 'votes' => 0]);

Note: When ssql is used, the insertGetId method is named as id by default. if you want to obtain the ID from other "sequences", you can pass the sequence name as the second parameter to the insertGetId method.

9. Update)

Of course, in addition to inserting records into the database, the query builder can use the update method to update existing records. The update method is the same as the insert method. the key-value pair for receiving columns and values contains the columns to be updated. you can use the where clause to constrain the update query:

DB::table('users')            ->where('id', 1)            ->update(['votes' => 1]);
Increase/decrease

The query builder also provides methods to increase or decrease the value of a given column name. Compared with writing update statements, this is a shortcut and provides a better experience and test interface.

Both methods receive at least one parameter: the column to be modified. The second parameter is optional and is used to control the number of column values that increase/decrease.

DB::table('users')->increment('votes');DB::table('users')->increment('votes', 5);DB::table('users')->decrement('votes');DB::table('users')->decrement('votes', 5);

During the operation, you can specify additional columns for update:

DB::table('users')->increment('votes', 1, ['name' => 'John']);
10. Delete)

Of course, the query builder can also delete records from the table using the delete method:

DB::table('users')->delete();

Before calling the delete method, you can add a where clause to restrict the delete statement:

DB::table('users')->where('votes', '<', 100)->delete();

If you want to clear the entire table, that is, delete all columns and set the auto-increment ID to 0, you can use the truncate method:

DB::table('users')->truncate();
11. pessimistic lock

The query builder also contains some methods to help you implement the "pessimistic lock" in the select statement ". You can use the sharedLock method in the query to include a "shared lock" when running the statement. The shared lock prevents the selected row from being modified until the transaction is committed:

DB::table('users')->where('votes', '>', 100)->sharedLock()->get();

You can also use the lockForUpdate method. The "for update" lock prevents the selected row from being modified or deleted by other shared locks:

DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.