laravel 數(shù)據(jù)庫(kù)
一、數(shù)據(jù)庫(kù)操作之DB facade
? ?在app->Http->Controllers目錄下新建一個(gè)Student控制器,StudentController.php。?StudentController.php代碼如下:
[php]?view plain?copy
namespace?App\Http\Controllers;??
use?Illuminate\Support\Facades\DB;??
class?StudentController?extends?Controller?{??
}??
? 1.查詢操作
? 在Student控制器里添加一個(gè)test1方法,查詢用的是DB類的靜態(tài)方法select(),參數(shù)是原生的sql語(yǔ)句,返回的是一個(gè)二維數(shù)組。dd()是laravel提供的方法,可以將一個(gè)數(shù)組以節(jié)點(diǎn)樹的形式展示出來(lái)。具體代碼如下:
[php]?view plain?copy
public?function?test1()??
{??
$student=DB::select("select?*?from?vipinfo");??
//返回一個(gè)二維數(shù)組??$student??
var_dump($student);??
//以節(jié)點(diǎn)樹的形式輸出結(jié)果??
dd($student);??
}??
路由配置:?Route::get('test1',['uses'=>'StudentController@test1']);? ?
URL訪問:http://localhost/laravel/public/index.php/test1 ,則會(huì)打印出結(jié)果。
?2.新增操作
新增使用的是DB類的靜態(tài)方法insert(),第一個(gè)參數(shù)是sql語(yǔ)句,第二個(gè)參數(shù)是一個(gè)數(shù)組,數(shù)組里放要插入的數(shù)據(jù)。這里?是占位符,通過(guò)數(shù)據(jù)庫(kù)接口層pdo的方式,達(dá)到防sql注入的目的。返回的是執(zhí)行的結(jié)果。插入成功則返回true,否則為false。
[php]?view plain?copy
$bool=DB::insert("insert?into?vipinfo(vip_ID,vip_name,vip_type,vip_fenshu)???
values(?,?,?,?)",[5,'小明','出行',670]);??
var_dump($bool);??
//新增成功則返回true。??
3. 更新操作
更新使用的是DB類的靜態(tài)方法update(),第一個(gè)參數(shù)是sql語(yǔ)句,第二個(gè)參數(shù)是一個(gè)數(shù)組,數(shù)組里的元素分別對(duì)應(yīng)sql語(yǔ)句里的問號(hào)。更新成功返回true。
[php]?view plain?copy
$bool=DB::update('update?vipinfo?set?vip_fenshu=???where?vip_ID=???',[700,5]);??
var_dump($bool);??//更新成功返回true??
4. 刪除操作
刪除使用的是DB類的靜態(tài)方法delete(),第一個(gè)參數(shù)是sql語(yǔ)句,第二個(gè)參數(shù)是一個(gè)數(shù)組,數(shù)組里的元素分別對(duì)應(yīng)sql語(yǔ)句里的問號(hào)。返回的是刪除的行數(shù)。
[php]?view plain?copy
$num=DB::delete('delete?from?vipinfo?where?vip_ID=??',[5]);??
echo?$num;??
二、數(shù)據(jù)庫(kù)操作之查詢構(gòu)造器
laravel查詢構(gòu)造器提供了方便流暢的接口,用來(lái)建立及執(zhí)行數(shù)據(jù)庫(kù)查找語(yǔ)法。使用了pdo參數(shù)綁定,使應(yīng)用程序免于sql注入,因此傳入的參數(shù)不需要額外轉(zhuǎn)義特殊字符?;旧峡梢詽M足所有的數(shù)據(jù)庫(kù)操作,而且在所有支持的數(shù)據(jù)庫(kù)系統(tǒng)上都可以執(zhí)行。
1.使用查詢構(gòu)造器實(shí)現(xiàn)增刪改查
同樣在Student控制器里測(cè)試以下代碼:
(1)新增
[php]?view plain?copy
$bool=DB::table("vipinfo")->insert(['vip_ID'=>6,'vip_name'=>'zls','vip_type'=>"出行",'vip_fenshu'=>800]);??
echo?$bool;??//返回bool值??
//如果想得到新增的id,則使用insertGetId方法??
$id=DB::table("vipinfo")->insertGetId(['vip_ID'=>5,'vip_name'=>'wyp','vip_type'=>"出行",'vip_fenshu'=>800]);??
echo?$id;??
//插入多條數(shù)據(jù)??
$bool=DB::table("vipinfo")->insert([??
['vip_ID'=>5,'vip_name'=>'wyp','vip_type'=>"出行",'vip_fenshu'=>800],??
['vip_ID'=>6,'vip_name'=>'zls','vip_type'=>"出行",'vip_fenshu'=>800],??
]);??
echo?$bool;??//返回bool值??
(2)修改
[php]?view plain?copy
$bool=DB::table("vipinfo")->where('vip_ID',6)->update(['vip_fenshu'=>500]);??
echo?$bool;??
//自增??
$bool=DB::table("vipinfo")->where('vip_ID',6)->increment("vip_fenshu");//自增1??
$bool=DB::table("vipinfo")->where('vip_ID',6)->increment("vip_fenshu",3);//自增3??
echo?$bool;??
//自減??
$bool=DB::table("vipinfo")->where('vip_ID',6)->decrement("vip_fenshu");//自1??
$bool=DB::table("vipinfo")->where('vip_ID',6)->decrement("vip_fenshu",3);//自增3??
echo?$bool;??
//自增時(shí)再修改其他字段??
$bool=DB::table("vipinfo")->where('vip_ID',6)->increment("vip_fenshu",3,['vip_name'=>'dbdibi']);//自增3??
(3)刪除
[php]?view plain?copy
$num=DB::table("vipinfo")->where('vip_ID',6)->delete();//刪除1條??
$num=DB::table("vipinfo")->where('vip_ID','>',4)->delete();//刪除多條??
echo?$num;??//刪除的行數(shù)??
$num=DB::table("vipinfo")->truncate();//刪除整表,不能恢復(fù),謹(jǐn)慎使用??
(4)查詢
[php]?view plain?copy
//get()返回多條數(shù)據(jù)??
$student=DB::table("vipinfo")->get();??
var_dump($student);????
//first()返回1條數(shù)據(jù)??
$student=DB::table("vipinfo")->first();??//結(jié)果集第一條記錄??
$student=DB::table("vipinfo")->orderBy('vip_ID','desc')->first();//按vip_ID倒序排序??
var_dump($student);????
//where()條件查詢??
$student=DB::table("vipinfo")->where('vip_ID','>=',2)->get();?//一個(gè)條件?????
$student=DB::table("vipinfo")->whereRaw('vip_ID>???and?vip_fenshu?>=??',[2,300])->get();?//多個(gè)條件??
dd($student);??
//pluck()指定字段,后面不加get??
$student=DB::table("vipinfo")->pluck('vip_name');??
dd($student);??
//lists()指定字段,可以指定某個(gè)字段作為下標(biāo)??
$student=DB::table("vipinfo")->lists('vip_name','vip_ID');???//指定vip_ID為下標(biāo)??
dd($student);??
$student=DB::table("vipinfo")->lists('vip_name');???//不指定下標(biāo),默認(rèn)下標(biāo)從0開始??
//select()指定某個(gè)字段??
$student=DB::table("vipinfo")->select('vip_name','vip_ID')->get();??
dd($student);??
//chunk()每次查n條??
$student=DB::table("vipinfo")->chunk(2,function($students){??//每次查2條??
var_dump($students);??
if(.......)?return?false;??//在滿足某個(gè)條件下使用return就不會(huì)再往下查了??
});??
2.使用聚合函數(shù)
[php]?view plain?copy
//count()統(tǒng)計(jì)記錄條數(shù)??
$nums=DB::table("vipinfo")->count();??
echo?$nums;??
//max()某個(gè)字段的最大值,同理min是最小值??
$max=DB::table("vipinfo")->max("vip_fenshu");??
echo?$max;??
//avg()某個(gè)字段的平均值??
$avg=DB::table("vipinfo")->avg("vip_fenshu");??
echo?$avg;??
//sum()某個(gè)字段的和??
$sum=DB::table("vipinfo")->sum("vip_fenshu");??
echo?$sum;??
四、數(shù)據(jù)庫(kù)操作之?- Eloquent ORM
1.簡(jiǎn)介、模型的建立及查詢數(shù)據(jù)
簡(jiǎn)介:laravel所自帶的Eloquent ORM?是一個(gè)ActiveRecord實(shí)現(xiàn),用于數(shù)據(jù)庫(kù)操作。每個(gè)數(shù)據(jù)表都有一個(gè)與之對(duì)應(yīng)的模型,用于數(shù)據(jù)表交互。
建立模型,在app目錄下建立一個(gè)Student模型,即Student.php,不需要帶任何后綴。
[php]?view plain?copy
namespace?App;??
use?Illuminate\Database\Eloquent\Model;??
class?Student?extends?Model{??
//指定表名??
protected?$table=?'vipinfo';??
//指定主鍵??
protected?$primaryKey=?'vip_ID';??
}??
在Student控制器里增加一個(gè)test3方法,配置路由Route::get('test3',['uses'=>'StudentController@test3']);
[php]?view plain?copy
public?function?test3(){??
//?all()方法查詢所有數(shù)據(jù)??
$studnets=Student::all();??
dd($studnets);??
//find()查詢一條,依據(jù)主鍵查詢。findOrFail()查找不存在的記錄時(shí)會(huì)拋出異常??
$student=Student::find(5);??//主鍵為5的記錄??
var_dump($student['attributes']);??
//查詢構(gòu)造器的使用,省略了指定表名??
$student=Student::get();????
var_dump($student);??
}??
2 . 新增數(shù)據(jù)、自定義時(shí)間戳、批量賦值
(1)使用save方法新增
laravel會(huì)默認(rèn)維護(hù)created_at,updated_at 兩個(gè)字段,這兩個(gè)字段都是存儲(chǔ)時(shí)間戳,整型11位的,因此使用時(shí)需要在數(shù)據(jù)庫(kù)添加這兩個(gè)字段。如果不需要這個(gè)功能,只需要在模型里加一個(gè)屬性:public $timestamps=false; 以及一個(gè)方法,可以將當(dāng)前時(shí)間戳存到數(shù)據(jù)庫(kù)
[php]?view plain?copy
protected?function?getDateFormat(){??
return?time();??
}??
這樣就不需要那兩個(gè)字段了。
控制器里寫:
[php]?view plain?copy
$student=new?Student();??
//設(shè)定數(shù)據(jù)??
$student->vip_name='xiaoming';??
$student->vip_type='出行';??
$student->vip_fenshu=900;??
$bool=$student->save();??//保存??
echo?$bool;??
從數(shù)據(jù)庫(kù)里取得某條記錄的時(shí)間戳?xí)r,默認(rèn)取得的是按日期格式化好的時(shí)間戳,如果想取得原本的時(shí)間戳,則在模型里增加asDateTime方法。
[php]?view plain?copy
protected?function?asDateTime($val){??
return?$val;??
}??
(2)使用create方法新增時(shí),需要在模型里增加:
[php]?view plain?copy
protected?$fillable=['vip_name','vip_fenshu','vip_type'];???//允許批量賦值的字段??
?控制器里寫:
[php]?view plain?copy
Student::create(['vip_name'=>'mmm','vip_fenshu'=>999,'vip_type'=>'出行']);??
這樣即可新增成功!
(3)firstOrCreate()以屬性查找記錄,若沒有則新增
[php]?view plain?copy
$student=Student::firstOrCreate(['vip_name'=>'mmm']);??
echo?$student;??
(4)firstOrNew()以屬性查找記錄,若沒有則會(huì)創(chuàng)建新的實(shí)例。若需要保存,則自己調(diào)用save方法()
[php]?view plain?copy
$student=Student::firstOrNew(['vip_name'=>'mmm']);??
$student->save();??
echo?$student;??
3. ?修改數(shù)據(jù)
[php]?view plain?copy
//通過(guò)模型更新數(shù)據(jù)??
$student=Student::find(2);??
$student->vip_fenshu=10000;??
$student->save();?//返回bool值??
//通過(guò)查詢構(gòu)造器更新??
$num=Student::where('vip_ID','>',2)->update(['vip_fenshu'=>2000]);??
echo?$num;??//返回更新的行數(shù)??
4. ?刪除數(shù)據(jù)
[php]?view plain?copy
//(1)通過(guò)模型刪除數(shù)據(jù)??
$student=Student::find(11);??
$student->delete();?//返回bool值??
//(2)通過(guò)主鍵刪除??
$num=Student::destroy(10);?//刪除主鍵為10的一條記錄??
echo?$num;?//返回刪除的行數(shù)??
$num=Student::destroy(10,5);?//刪除多條??或者$num=Student::destroy([10,5]);??
echo?$num;?//返回刪除的行數(shù)?
laravel查詢數(shù)據(jù)
從數(shù)據(jù)表中取得所有的數(shù)據(jù)列
$users=DB::table('users')->get();foreach($usersas$user){var_dump($user->name);}
從數(shù)據(jù)表中分塊查找數(shù)據(jù)列
DB::table('users')->chunk(100,function($users){foreach($usersas$user){//}});
1.分表查詢、
$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();
2.還有關(guān)聯(lián)查詢表
$user=member::leftjoin("user","member.m_id","=","user.u_id")
? ?->where("member.wbc_code","index")
?->where();
->select("添加顯示的字段")
->get();獲取所有查詢條件的數(shù)據(jù)
如果用first()方法只獲取到單條查詢數(shù)據(jù)
3.通過(guò)在閉包中返回false來(lái)停止處理接下來(lái)的數(shù)據(jù)列:
DB::table('users')->chunk(100,function($users){//returnfalse;});
3.1從數(shù)據(jù)表中取得單一數(shù)據(jù)列
$user=DB::table('users')->where('name','John')->first();var_dump($user->name);
3.2從數(shù)據(jù)表中取得單一數(shù)據(jù)列的單一字段
$name=DB::table('users')->where('name','John')->pluck('name');
取得單一字段值的列表
$roles=DB::table('roles')->lists('title');
4.這個(gè)方法將會(huì)返回?cái)?shù)據(jù)表 role 的 title 字段值的數(shù)組。你也可以通過(guò)下面的方法,為返回的數(shù)組指定自定義鍵值。
$roles=DB::table('roles')->lists('title','name');
4.1指定查詢子句 (Select Clause)
$users=DB::table('users')->select('name','email')->get();$users=DB::table('users')->distinct()->get();$users=DB::table('users')->select('name as user_name')->get();
4.2增加查詢子句到現(xiàn)有的查詢中
$query=DB::table('users')->select('name');$users=$query->addSelect('age')->get();
4.3使用 where 及運(yùn)算符
$users=DB::table('users')->where('votes','>',100)->get();
4.4「or」語(yǔ)法
$users=DB::table('users')->where('votes','>',100)->orWhere('name','John')->get();
5使用 Where Between
$users=DB::table('users')->whereBetween('votes',[1,100])->get();
6.使用 Where Not Between
$users=DB::table('users')->whereNotBetween('votes',[1,100])->get();
7.使用 Where In 與數(shù)組
$users=DB::table('users')->whereIn('id',[1,2,3])->get();$users=DB::table('users')->whereNotIn('id',[1,2,3])->get();
8.使用 Where Null 找有未配置的值的數(shù)據(jù)
$users=DB::table('users')->whereNull('updated_at')->get();
Dynamic Where Clauses
You may even use "dynamic" where statements to fluently build where statements using magic methods:
$admin=DB::table('users')->whereId(1)->first();$john=DB::table('users')->whereIdAndEmail(2,'john@doe.com')->first();$jane=DB::table('users')->whereNameOrAge('Jane',22)->first();
9.排序(Order By)、分群(Group By) 及 Having
$users=DB::table('users')->orderBy('name','desc')->groupBy('count')->having('count','>',100)->get();
10.偏移(Offset) 及 限制(Limit)
$users=DB::table('users')->skip(10)->take(5)->get();