laravel - query builder

retrieve data

1, the data acquired from all the rows in the table

<?php

class UserController extends Controller{

       public function index(){

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

      }

}

Obtained from the data in the table row of data you can use the first method. This method returns a target stdclass

$user = DB::table("users")->where(“name”,"John")->first()

If no positive data line, it can be used to retrieve a single value from the values ​​in the record. This method returns the field Found:

$email = DB::table('users')->where("name","John")->value("email");

Get an Found, pluck method can be used. In the following example too, we will get the role of the table was a collection to give the title

$titles = DB::table("roles")->pluck("title");

foreach($titles as $title){

       echo $title;  

}

You can also return to get the specified field in the collection was the custom keys:

$roles = DB::table("roles")->pluck("title","name")

foreach($roles as $name=>$title){

            echo $title;

}

2, the results of block

If you need to deal with thousands of database records. You may consider using chunk method. The primary method of obtaining a result set too small, and passed to the closure function processing. This method Artisan command to write thousands of data processing time was very useful. We can try to cut all the data table 100 recording a processing to obtain a piece of:

DB::table("users)->orderBy("id")->chunk(100,function($users){

          foreach($users as $user){

          }

})

You can continue to acquire block terminated by returning false results in the closure:

DB::table('users')->orderBy('id')->chunk(100,function(){

        return false;

})

polymerization

Query builder also provides various polymerization methods, such as count, max, min, avg well sum. You can call any method after construct a query:

$user = DB:table("users")->count():

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

Of course, you can also get these polymerization methods and other query combination:

$price = DB::table('orders')->where("finalized",1)->avg('price');

3, it is determined whether the record exists

In addition count method can determine the result of the query was whether or not there, you can also use exists and doesntExist method:

return DB::table('orders')->where("finalized",1)->exists();

return DB::table("orders")->where('finalized',1)->doesntExist();

selects statement

Specifies a select statement

Of course, you may not always want to get all the columns from the data table. Use the select method, you can customize a select query to query specific fields:

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

distinct method will force the query returns results do not have to repeat:

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

If you already have a query builder instance, and want to join an existing field in the query too, then you can use the method addSelect

$query = DB::table('users')->select('name');

$users = $query->addSelect('age')->get();

4, native expression

Sometimes you may need to use the native expression in the query. You can use DB: raw create a native expression:

$users = DB::table('users')

              ->select(DB::raw(‘count(*) as user_count , status ’))

              ->where('status' , '<>' , 1)

               ->groupBy("status")

               ->get();

Note: The original expression will be injected into the query as a string, so you should be used with care, to avoid creating SQL injection vulnerabilities have

Primeval way

The following methods may be used instead of DB :: RAW  , The native query expressions into the respective portions obtained.

selectRow method can replace select (DB :: raw (...) ). The method to obtain the second parameter is optional, is the value of a binding parameter array obtained:

$order = DB::table('orders')

               ->selectRaw('price * ? as price_with_tax ' , [1.0825])

               ->get();

whereRaw/orWhereRaw

The native methods and orWhereRaw whereRaw obtained where

You have to be injected into the query. These two methods have the second parameter is optional, value or have an array of binding parameters:

$orders = DB::table('orders')

                ->whereRaw(' price > IF(state = "TX" , ? , 100) ' , [200] )

                ->get();

Note: Data conversion  

       The data into an array toArray ()

       The data into json toJson ()

 

Guess you like

Origin www.cnblogs.com/shangfz/p/11579533.html