laravel框架數(shù)據(jù)庫操作、查詢構建器、Eloquent ORM操作實例分析
本文實例講述了laravel框架數(shù)據(jù)庫操作、查詢構建器、Eloquent ORM操作。分享給大家供大家參考,具體如下:
1、連接數(shù)據(jù)庫
laravel連接數(shù)據(jù)庫的配置文件位于config/database.php中,在其中connection字段中包含laravel所支持的數(shù)據(jù)庫的配置信息,可以看到其中有主機、端口、數(shù)據(jù)庫、用戶名、密碼等信息:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
其中都是引入env文件中的默認值,laravel目錄最外層有.env文件,在其中配置對應的默認值
DB_HOST=數(shù)據(jù)庫服務器地址
DB_PORT=數(shù)據(jù)庫端口
DB_DATABASE=數(shù)據(jù)庫名
DB_USERNAME=用戶名
DB_PASSWORD=密碼
2、原生SQL操作數(shù)據(jù)庫
在controller中對數(shù)據(jù)庫進行增刪改查的操作
public static function testDB(){
//增加一條數(shù)據(jù)
DB::insert("insert into student(name,age) values(?,?)",['sandy',19]);
//刪除一條數(shù)據(jù)
DB::delete('delete from student where name=?',['sandy']);
//修改一條數(shù)據(jù)
DB::update('update student set sex=? where name=?',['男','tory']);
//查詢數(shù)據(jù)
$res=DB::select('select * from student');
//進行數(shù)據(jù)庫通用操作
DB::statement('drop table users');
//打印結果
dd($res);
}
其中通過?占位符的方式進行了參數(shù)綁定,以此來防止數(shù)據(jù)庫注入攻擊,也可以通過命名綁定的方式:
$res = DB::select('select * from users where id = :id', ['id' => 1]);
3、通過查詢構建器操作數(shù)據(jù)庫
Laravel將常用的數(shù)據(jù)庫操作封裝為接口函數(shù)提供給用戶調(diào)用,從而使數(shù)據(jù)庫操作更為便捷,這些接口就是查詢構建器(query builder)。而且通過PDO綁定的方式避免SQL注入攻擊,在使用查詢構建器時不必考慮過濾用戶輸入。
3.1、得到結果集
lavarel查詢的返回結果集合是StdClass,可以通過$res->name類似訪問對象屬性的方式訪問返回值。如果要查詢整個表使用get(),查詢表中一條數(shù)據(jù)使用first(),查詢一條數(shù)據(jù)的某個字段用value(),查詢表中所有數(shù)據(jù)的某個字段用pluck()
//get()返回表中所有數(shù)據(jù)
$res=DB::table('student')->get();
//first()返回結果集中的第一條數(shù)據(jù)
$res=DB::table('student')->where('id','1001')->first();
//value()返回一條數(shù)據(jù)中的指定字段
$res=DB::table('student')->where('id','1003')->value('name');
//pluck()返回結果集中name字段的所有值
$res=DB::table('student')->pluck('name');
當結果集中的數(shù)據(jù)過多時,可以通過分塊的方式返回結果集,chunk函數(shù)第一個參數(shù)為分塊的大小(以每塊2個數(shù)據(jù)的方式返回結果集),第二個參數(shù)為回調(diào)函數(shù),當其返回false時就停止結果集的返回:
DB::table('student')->chunk(2,function ($res){
foreach ($res as $user){
var_dump($user);
if ($user->id >=1003) return false;
}
});
3.2、增刪改查
//增加一條數(shù)據(jù)
DB::table('student')->insert(['name'=>'李four','sex'=>'男','age'=>22]);
//增加多條數(shù)據(jù)
DB::table('student')->insert([
['name'=>'wang五','sex'=>'女','age'=>21],
['name'=>'zhao六','sex'=>'女','age'=>20],
]);
//刪除數(shù)據(jù)
DB::table('student')->where('id','>=',1006)->delete();
//刪除整個表
DB::table('student')->truncate();
//修改數(shù)據(jù)
DB::table('student')->where('id',1005)->update(['sex'=>'女','age'=>21]);
//自增increment、自減decrement,默認增1
DB::table('student')->where('id',1005)->increment('age',2);
//自增同時可以進行修改
DB::table('student')->where('id',1005)->increment('age',1,['sex'=>'女']);
//查詢指定字段
$res=DB::table('student')->select('name','age')->get();
3.3、查詢條件
通過查詢構建器的where方法可以添加數(shù)據(jù)庫查詢條件,where()接收三個參數(shù):字段名、操作符、值,操作符如果是'='可以省略,例如查詢id>=1003的數(shù)據(jù):
$res=DB::table('student')->where('id','>=',1003)->get();
也可以通過條件數(shù)組傳入多個限制條件,比如查詢id>=1003并且id<1005:
$res=DB::table('student')->where([
['id','>=',1003],
['id','<',1005]
])->get();
通過orwhere()來連接兩個并列條件,例如查詢id>=1003或者id<1002的數(shù)據(jù):
$res=DB::table('student')->where('id','>=',1003)->orwhere('id','<',1002)->get();
whereBetween()查詢位于某個區(qū)間的數(shù)據(jù):
$res=DB::table('student')->whereBetween('id',[1003,1006])->get();
當when()來判斷某個查詢是否執(zhí)行,例如當$order為true時,才會執(zhí)行排序:
$order=false;
$res=DB::table('student')->when($order,function ($query){
return $query->orderBy('age','desc'); //$order為true時才執(zhí)行此語句
})->get();
3.4、排序、分組、限定
//orderBy對age字段升序
$res=DB::table('student')->orderBy('age','asc')->get();
//按照create_at字段進行時間排序
$res=DB::table('student')->latest('create_at')->get();
//分組
$res=DB::table('student')->groupBy('sex')->get();
//跳過一條數(shù)據(jù)后返回2條數(shù)據(jù)
$res=DB::table('student')->skip(1)->limit(2)->get();
3.5、聚合函數(shù)
laravel查詢構建器還提供了聚合函數(shù)用于操作查詢的結果集,包括count(計數(shù))、sum(求和)、avg(平均值)、max(最大值)、min(最小值),例如求年齡平均值:
$res=DB::table('student')->avg('age');
4、Eloquent ORM
ORM是對象關系映射(Object Relational Mapping)的簡稱,是一種實現(xiàn)面向對象編程語言里不同類型系統(tǒng)的數(shù)據(jù)之間的轉換的技術,即將數(shù)據(jù)庫中的數(shù)據(jù)按照對象的形式進行組織,可以便于面向對象的程序進行數(shù)據(jù)庫操作,之前在學習mongoDB時使用過mongoose ORM組織mongoDB ,當時還沒有意識到這是orm。
Laravel內(nèi)置的Eloquent ORM提供了一種便捷的方式幫助你組織數(shù)據(jù)庫數(shù)據(jù),每張數(shù)據(jù)表都對應一個與該表進行交互的模型(Model),通過Model類,你可以對數(shù)據(jù)表進行查詢、插入、更新、刪除等操作。Eloquent ORM本質(zhì)上是查詢構建器,因此上面查詢構建器所使用的方法Eloquent都可以使用。
4.1、創(chuàng)建Model
在app文件夾下新建model文件,每個數(shù)據(jù)庫都需要對應一個model,例如創(chuàng)建一個Student模板類:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
//指定對應的表
protected $table='student';
//指定主鍵
protected $primaryKey='id';
//允許批量賦值的字段
protected $fillable=['name','age'];
//不允許批量賦值的字段
protected $guarded=['created_at'];
}
模板類會默認對應小寫首字母末尾加s的數(shù)據(jù)庫,例如Student模板會在當前數(shù)據(jù)庫中查找students表。如果需要自定義表名,則需要重寫$table變量來指定表名。
Eloquent默認的主鍵為'id',且該字段為自增int型,如果需要自定義主鍵,可以通過$primaryKey來指定。
Eloquent默認會管理數(shù)據(jù)表的創(chuàng)建時間、更新時間,對應數(shù)據(jù)表中的created_at、updated_at字段,你需要在創(chuàng)建表時包含這兩個字段。如果不需要管理,可以令public $timestamps = false;。否則會報錯
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list'
也可以自定義兩個時間為你數(shù)據(jù)庫中的字段:
const CREATED_AT = 'my_create'; const UPDATED_AT = 'my_update';
4.2、Eloquent操作數(shù)據(jù)庫
- 新增數(shù)據(jù)有兩種方法,一是通過新建ORM實例,而是通過create方法。在使用create批量添加時,需要在模板中通過$fillable指定可以賦值的字段,也可以$guard指定不允許賦值的字段。
//新建實例并賦值、保存 $stu=new Student(); $stu->name='orm2'; $stu->save(); //create方法批量添加數(shù)據(jù) Student::create(['name'=>'orm3','age'=>13]);
- 刪除數(shù)據(jù)也有兩種方法,一是通過find方法刪除指定主鍵,二是通過查詢構建器:
//destroy刪除指定主鍵值
Student::destroy(1006,1007);
//通過查詢構建器刪除
Student::where('id',1008)->delete();
- 修改數(shù)據(jù):①通過ORM實例來修改并保存②通過查詢構建器
//通過返回Student對象進行修改
$stu=Student::find(1005);
$stu->age=21;
$stu->save();
//通過查詢構建器修改
Student::where('id',1005)->update(['age'=>22]);
- 查找數(shù)據(jù):
//查詢表中所有記錄 $table=Student::all(); //根據(jù)id查詢一條數(shù)據(jù) $row=Student::find(1002); dd($table);
當然也可以通過構建器的get()、first()來獲取數(shù)據(jù)
通過上面的增刪改查可以看出Eloquent可以使用查詢構建器的所有方法,除了增刪改查外,還有where、聚合函數(shù)等。
更多關于Laravel相關內(nèi)容感興趣的讀者可查看本站專題:《Laravel框架入門與進階教程》、《php優(yōu)秀開發(fā)框架總結》、《php面向對象程序設計入門教程》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家基于Laravel框架的PHP程序設計有所幫助。
相關文章
Codeigniter框架的更新事務(transaction)BUG及解決方法
這篇文章主要介紹了Codeigniter框架的更新事務(transaction)BUG及解決方法,具體BUG和解決辦法在文中有詳細描述,需要的朋友可以參考下2014-07-07
一次項目中Thinkphp繞過禁用函數(shù)的實戰(zhàn)記錄
這篇文章主要給大家介紹了一次項目中Thinkphp繞過禁用函數(shù)的實戰(zhàn)記錄,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2021-11-11
destoon實現(xiàn)調(diào)用圖文新聞的方法
這篇文章主要介紹了destoon實現(xiàn)調(diào)用圖文新聞的方法,是非常實用的技巧,需要的朋友可以參考下2014-08-08
php+jQuery.uploadify實現(xiàn)文件上傳教程
這篇文章主要介紹了php+jQuery.uploadify實現(xiàn)文件上傳教程,需要的朋友可以參考下2014-12-12

