There are three types of Laravel operations database: DB native SQL, builder, Model. These three kinds of decisions are more appropriate depending on the situation.
So today we start with the DB native sql:
1 operation with DB façade native SQL statement
Using the DB façade operation is nothing more than: Insert, select, UPDATE, delete additional statement (general statements such as drop, etc.).
1.1 Insert
Public function Getinsert () { DB:: Insert (' INSERT into articles (title, body) VALUE (?,?) ', [' Learn Laravel ', ' Balablalabalabla ']); }
The Insert method accepts two parameters The first argument is the native SQL statement, and the second parameter is an array of corresponding SQL statements?
1.2 Select
Public functionGetarticles () {$articles= Db::select (' select * from articles WHERE title=:title ', [' title ' = = ' Learn Laravel ']); foreach($articles as $article){ Echo"<p>$article->id</p> "; Echo"<p>$article->title</p> "; Echo"<p>$article->body</p> "; } }
Our placeholder is more than just? You can also use ": Name" to indicate that the corresponding array is a pair of children's key value.
1.3 Update
Public function getUpdate () { $affected = db::update (' Update articles SET title=:title,body=:body WHERE id=:id ', [' title ' = = ') Laravel database ', ' body ' = ' balabala ', ' id ' = 1]); Echo $affected ; }
The Update method also returns a affected that is the total number of rows affected.
1.4 Delete
Public function Getdelete () { $affected = DB::d elete (' Delete from articles WHERE id=:id ', [' id ' = 2]); Echo $affected ; }
1.5 Statement
Public function Getdrop () { DB:: Statement (' DROP TABLE articles '); }
2 Monitoring Queries
We can use the Listen method to listen to every action database action, so we can be used to record the log AH debugging AH what:
classAppserviceproviderextendsserviceprovider{/** * Bootstrap any application services. * * @return void*/ Public functionboot () {DB:: Listen (function($sql,$bindings,$time){ //$sql = Query statement//$bindings = Bound key and value array type//time spent }); } /** * Register any application services. * * @return void*/ Public functionRegister () {// }}
Laravel5.1 database--db running native SQL