一、ORM操作需要創(chuàng)建對應(yīng)的model
1.直接在model操作:class User extends Eloquent
2.依賴注入方式:如圖

image.png
二、有兩種方式使用數(shù)據(jù)操作對象
- 使用new關(guān)鍵字創(chuàng)建對象后執(zhí)行對象的方法
- 直接調(diào)用static方法(實(shí)際并發(fā)靜態(tài)方法,而是fascade生成的)
三、常用的數(shù)據(jù)操作
VirtualBourse::find(1) //查詢單條數(shù)據(jù)
VirtualBourse::all() //查詢所有數(shù)據(jù)
VirtualBourse::pluck('symbol_id') //指定查詢表中的一個字段
VirtualBourse::find(1)->delete() //刪除單條數(shù)據(jù)VirtualBourse::estory(array(1,2,3)) //刪除單條或多條數(shù)據(jù)
VirtualBourse::save() //保存數(shù)據(jù)
VirtualBourse::first() //取第一條數(shù)據(jù)
VirtualBourse::where('name', 'admin')->update(array('name' => 'zoe')); //指定條件,更新數(shù)據(jù)
VirtualBourse::truncate() //清空數(shù)據(jù)表,危險(xiǎn)操作
VirtualBourse::where('name', 'admin')->get(array('id','title')); //指定查詢條件獲取多條數(shù)據(jù)
VirtualBourse::pluck('title'); //返回表中該字段的第一條記錄
VirtualBourse::lists('artist') //返回一列數(shù)據(jù)
VirtualBourse::where('artist', 'Something Corporate')->toSql(); //獲取查詢的sql語句,僅用于條件,不能帶get()之類帶查詢結(jié)果的
條件查詢:
1. 最普通的條件查詢 User::where('字段名','查詢字符','限制條件') 例:Album::where('title', 'LIKE', '...%')
2. 多條件查詢,使用多個where Album::where('title', 'LIKE', '...%')->where('artist', '=', 'Say Anything')->get();
3. 或查詢操作使用orWhere(),使用方法通where
4.直接用sql語句寫查詢條件 Album::whereRaw('artist = ? and title LIKE ?', array('Say Anything', '...%'))
5. 其他查詢方法
whereIn(),whereBetween(),whereNested()子查詢,orWhereNested(),whereNotIn(),whereNull(),whereNotNull()
6. 快捷方式 whereUsername('king') 查詢'username' = 'king'的數(shù)據(jù),默認(rèn)系統(tǒng)無此方法,username為字段名稱
結(jié)果排序:
使用order關(guān)鍵字:
Album::where('artist', '=', 'Matt Nathanson')->orderBy('year')->get(); 默認(rèn)asc
orderBy('year', 'desc')
限制結(jié)果數(shù)量
take()方法
Album::take(2)->get(); //select * from `albums` limit 2
指定偏移
Album::take(2)->skip(2)->get(); //select * from `albums` limit 2 offset 2
whereRaw($where)->skip($limit)->take($pageSize)->get();
//查詢?nèi)コ齣d重復(fù)后的數(shù)量
function getUserCount(){
return $this->distinct('id')->count('id');
}