Laravel提供了3種操作數(shù)據(jù)庫(kù)方式:DB facade(原始方式)、查詢構(gòu)造器和Eloquent ORM哥放。
數(shù)據(jù)庫(kù)的配置文件在config目錄下的database.php里。打開這個(gè)文件旭绒,找到mysql的配置項(xiàng)严拒。
這里有個(gè)env,它其實(shí)是調(diào)用了laravel根目錄下的.env文件荠呐,這個(gè)文件存儲(chǔ)了數(shù)據(jù)庫(kù)的配置信息赛蔫。打開它。修改為項(xiàng)目的數(shù)據(jù)庫(kù)信息即可泥张。
請(qǐng)自行建一個(gè)數(shù)據(jù)庫(kù)呵恢,其中數(shù)據(jù)庫(kù)得包含vipinfo表,并且插入一些數(shù)據(jù)媚创,以方便下面使用渗钉。表的結(jié)構(gòu)如下圖。
顧名思義:這張表是會(huì)員表钞钙,分別有會(huì)員ID(主鍵)鳄橘,會(huì)員名字,會(huì)員類型芒炼,會(huì)員積分等字段挥唠。
一、數(shù)據(jù)庫(kù)操作之DB facade
在app->Http->Controllers目錄下新建一個(gè)Student控制器焕议,StudentController.php宝磨。 StudentController.php代碼如下:
<?php
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)窿祥。具體代碼如下:
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訪問(wèn):http://localhost/laravel/public/index.php/test1 ,則會(huì)打印出結(jié)果蝙寨。
2.新增操作
$bool=DB::insert("insert into vipinfo(vip_ID,vip_name,vip_type,vip_fenshu)
values(?,?,?,?)",[5,'小明','出行',670]);
var_dump($bool);
//新增成功則返回true晒衩。
- 更新操作
更新使用的是DB類的靜態(tài)方法update()嗤瞎,第一個(gè)參數(shù)是sql語(yǔ)句,第二個(gè)參數(shù)是一個(gè)數(shù)組听系,數(shù)組里的元素分別對(duì)應(yīng)sql語(yǔ)句里的問(wèn)號(hào)贝奇。更新成功返回true。
$bool=DB::update('update vipinfo set vip_fenshu= ? where vip_ID= ? ',[700,5]);
var_dump($bool); //更新成功返回true
-
刪除操作
刪除使用的是DB類的靜態(tài)方法delete()靠胜,第一個(gè)參數(shù)是sql語(yǔ)句掉瞳,第二個(gè)參數(shù)是一個(gè)數(shù)組,數(shù)組里的元素分別對(duì)應(yīng)sql語(yǔ)句里的問(wèn)號(hào)浪漠。返回的是刪除的行數(shù)陕习。
$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)義特殊字符损合。基本上可以滿足所有的數(shù)據(jù)庫(kù)操作歌粥,而且在所有支持的數(shù)據(jù)庫(kù)系統(tǒng)上都可以執(zhí)行塌忽。
1.使用查詢構(gòu)造器實(shí)現(xiàn)增刪改查
同樣在Student控制器里測(cè)試以下代碼:
(1)新增
$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)修改
$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)刪除
$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)查詢
//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ù)
//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
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']);
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ù)
protected function getDateFormat(){
return time();
}
這樣就不需要那兩個(gè)字段了挺狰。
控制器里寫:
$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方法。
protected function asDateTime($val){
return $val;
}
(2)使用create方法新增時(shí)始绍,需要在模型里增加:
protected $fillable=['vip_name','vip_fenshu','vip_type']; //允許批量賦值的字段
控制器里寫:
Student::create(['vip_name'=>'mmm','vip_fenshu'=>999,'vip_type'=>'出行']);
這樣即可新增成功瞳购!
(3)firstOrCreate()以屬性查找記錄,若沒有則新增
$student=Student::firstOrCreate(['vip_name'=>'mmm']);
echo $student;
(4)firstOrNew()以屬性查找記錄亏推,若沒有則會(huì)創(chuàng)建新的實(shí)例学赛。若需要保存,則自己調(diào)用save方法()
$student=Student::firstOrNew(['vip_name'=>'mmm']);
$student->save();
echo $student;
- 修改數(shù)據(jù)
//通過(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ù)
- 刪除數(shù)據(jù)
//(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ù)