thinkphp5中怎么操作數(shù)據(jù)庫,進(jìn)行增刪改查?下面本篇文章就來帶大家詳細(xì)了解一下thinkphp5中增刪改查數(shù)據(jù)庫的方法,希望對(duì)大家有所幫助!
thinkphp標(biāo)準(zhǔn)數(shù)據(jù)表設(shè)計(jì):創(chuàng)建時(shí)間字段:create_time更新時(shí)間字段:update_time刪除時(shí)間字段:delete_time?類型選int,如下圖:
【相關(guān)教程推薦:thinkphp框架】
一、創(chuàng)建model的文件夾
在application文件夾下的二級(jí)對(duì)象目錄中新建名為model的文件夾,該文件夾與對(duì)應(yīng)的controller和view目錄同級(jí),如下圖:
立即學(xué)習(xí)“PHP免費(fèi)學(xué)習(xí)筆記(深入)”;
如果有多個(gè)模塊(比如前臺(tái)index,后臺(tái)admin),操作的數(shù)據(jù)庫都差不多,那么可以把model模型放到common公共模塊里,如下:
二、創(chuàng)建model模型類
1、在model目錄下創(chuàng)建model對(duì)象文件,一般model的名字和表名是對(duì)應(yīng)的,例如:
表名?pre_user???????--------------->??模型名?User.php 表名?pre_user_info??--------------->??模型名?UserInfo.php
?2、定義model模型
<?php namespace appindexmodel; use thinkModel; use thinkDb; class User extends Model{ /** * 定義變量 * 1.變量名稱應(yīng)與數(shù)據(jù)表中的字段名相同 * 2.此處可根據(jù)需求省略,因?yàn)槿绻麤]有,thinkphp會(huì)自動(dòng)在數(shù)據(jù)表中尋找的對(duì)應(yīng)字段名 */ public $username; public $password; } ?>
3、如果數(shù)據(jù)模型定義名和表名不一致,那么就需要額外定義和聲明,如下:
<?php namespace appindexmodel; use thinkModel; use thinkDb; class User extends Model { protected $table = "admin_user";//指定數(shù)據(jù)表名 protected $pk = 'id'; //指定主鍵的字段 } ?>
三、調(diào)用model模型的方法
//導(dǎo)入定義的數(shù)據(jù)模型類 use?appindexmodelUser; //方法一: $res?=?User::get(1); //方法二: $user?=?new?User; $res?=?$user::get(1); //方法三: use?thinkLoader; $user?=?Loader::model("User"); $res?=?$user::get(1); //方法四: $user?=?model("User");??????? $res?=?$user::get(1);
四、查詢操作
get 獲取一條記錄
$res?=?User::get(1);
all 獲取多條記錄
1、不傳參
$result?=?User::all();?//查詢出所有記錄
2、參數(shù)為n,n為正整數(shù)?
$result?=?User::all(1);?//查詢出id為1的記錄
3、參數(shù)為’n1, n2, n3…’
$result?=?User::all('7,?8,?9,?10');?//查詢出id為7、8、9、10的4條記錄
4、參數(shù)為[n1, n2, n3…]?
$result?=?User::all([7,?8,?9,?10]);?//查詢出id為7、8、9、10的4條記錄
find 查詢某一條
?$res?=?User::where('id','1')->field('name')->find();
?不等于
->where(‘id’,’neq’,1)
select 多條查詢
$res?=?User::where('id','1')->field('name')->limit(2)->order('id?DESC')->select();
value 按字段查詢一條
$res?=?User::where('id','1')->value('name');
將結(jié)果轉(zhuǎn)換成數(shù)組
$res?=?$res->toArray();
查詢數(shù)目
//查詢總條數(shù) $res?=?User::count(); //按條件統(tǒng)計(jì)條數(shù) $res?=?User::where('id','>',3)->count();
whereTime() 時(shí)間條件查詢
1、獲取今天的信息
db('table')->whereTime('c_time',?'today')->select(); //也可以簡化為下面方式 db('table')->whereTime('c_time',?'d')->select();
2、獲取昨天的信息
db('table')->whereTime('c_time',?'yesterday')->select();
3、獲取本周的信息
db('table')->whereTime('c_time',?'week')->select();??? //也可以簡化為下面方式 db('table')->whereTime('c_time',?'w')->select();
4、獲取本月的信息
db('table')->whereTime('c_time',?'month')->select();??? //也可以簡化為下面方式 db('table')->whereTime('c_time',?'m')->select();
?5、獲取上月的信息
db('table')->whereTime('c_time','last?month')->select();
6、獲取今年的信息
db('table')->whereTime('c_time',?'year')->select();???? //也可以簡化為下面方式 db('table')->whereTime('c_time',?'y')->select();
?7、獲取去年的信息
db('table')->whereTime('c_time','last?year')->select();
8、日期區(qū)間查詢
//根據(jù)時(shí)間戳查詢今天到后天 db('table')->whereTime('time',?'between',?[strtotime(date('Y-m-d')),?strtotime(date('Y-m-d',?strtotime('+2?day')))])->select(); 根據(jù)日期查詢今天到后天 db('table')->whereTime('time',?'between',?['2020-3-28',?'2020-3-30'])->select();
五、添加操作
1、使用create()方法添加
$res?=?User::create([ ?????'name'??????=>?'安陽', ?????'age'???????=>?23, ?????'sex'???????=>?1, ?????'password'??=>?'123456' ?]);
2、添加數(shù)據(jù),并返回添加的主鍵
$uid=UserModel::create([ ?????'name'??????=>?'安陽', ?????'age'???????=>?23, ?????'sex'???????=>?1, ?????'password'??=>?'123456' ?])->id;
也可以使用DB類的insertGetId方法,如下:
$uid?=?User::insertGetId([ ?????'name'??????=>?'安陽', ?????'age'???????=>?23, ?????'sex'???????=>?1, ?????'password'??=>?'123456' ?]);
3、實(shí)例化方式添加
?$user?=?new?User; ?$user->name?=??'安陽'; ?$user->age?=??23; ?$user->save();
4、實(shí)例化方式過濾插入字段,返回插入行數(shù)
?$user?=?new?User; ?$data?=?[ ?????'name'?=>?'安陽', ?????'age'?=>?23, ?????'email'?=>?'123456@qq.com' ?]; ?//只有name和age字段會(huì)寫入 ?$res?=?$user->allowField(['name',?'age'])->save($data);
5、模型使用allowField()過濾非數(shù)據(jù)表字段的數(shù)據(jù)
//定義模型對(duì)象,并傳入post數(shù)據(jù) $user?=?new?User($_POST); //過濾post數(shù)組中的非數(shù)據(jù)表字段數(shù)據(jù) $user->allowField(true)->save();
6、模型使用allowField()指定某些字段寫入
$user?=?new?User; //?post數(shù)組中只有name和email字段會(huì)寫入 $user->allowField(['name','email'])->save($_POST,?['id'?=>?1]);
7、批量添加使用saveAll()
user?=?new?User; $list?=?[ ????['name'=>'安陽','email'=>'thinkphp@qq.com'], ????['name'=>'小柒','email'=>'12345678@qq.com'] ?]; $user->saveAll($list);
也可以使用DB類的insertAll()方法,返回添加成功的條數(shù)?
$res?=?User::insertAll([ ?????'name'??????=>?'安陽', ?????'age'???????=>?23, ?????'sex'???????=>?1, ?????'password'??=>?'123456' ?]);
補(bǔ)充,過濾字段的其他方法:
1、在DB操作中,可以使用 strict 關(guān)閉字段嚴(yán)格檢查
Db::name(‘user’)->strict(false)->insert($data);2、使用php的 unset() 方法銷毀變量
unset($data[‘file’]);
6、saveAll添加多條數(shù)據(jù),返回對(duì)象列表
?$user?=?new?User; ?$data?=?[ ?????[ ?????????'name'?=>?'安陽', ?????????'age'?=>?20, ?????????'email'?=>?'123456@qq.com' ?????], ?????[ ?????????'name'?=>?'小柒', ?????????'age'?=>?25, ?????????'email'?=>?'ap555@qq.com' ?????] ?]; ?$res?=?$user->allowField(['name',?'age'])->saveAll($data);
六、更新操作
1、update 返回影響行數(shù)
?$res?=?User::where(['id'=>1])->update(['name'=>'安陽']);
2、setField 單獨(dú)更新某個(gè)字段
User::where('id',1)->setField('name','安陽');
3、setInc
//setInc('money',10)表示將money字段加上10 User::where(['id'=>1])->setInc('money',?10);
4、setDec
//setDec('money',10)表示將money字段減去10 User::where(['id'=>1])->setDec('money',?10);
5、批量更新,要求數(shù)據(jù)中含有主鍵,返回更新對(duì)象列表
$user?=?new?User; $res?=?$user->saveAll([ ?????['id'=>1,?'name'?=>?'安陽'], ?????['id'=>2,?'name'?=>?'小柒'] ?]);
七、刪除操作
1、傳入主鍵,返回影響行數(shù)
$res?=?User::destroy(1);
2、傳入條件,返回影響行數(shù)
?$res?=?User::destroy(['name'=>'安陽']);
3、條件刪除 返回影響行數(shù)
?$res?=?User::where(['id'=>1])->delete();
八、事務(wù)
1、自動(dòng)控制事務(wù)處理
Db::transaction(function(){? ????Db::table('order')->where(['id'=>1])->delete();? Db::table('user')->where('id'=>1)->setInc('money',10); });
2、手動(dòng)控制事務(wù)
Db::startTrans();//啟動(dòng)事務(wù) try?{ ????Order::where(['id'=>1])->delete(); User::where('id'=>1)->setInc('money',10); Db::commit();//提交事務(wù) }?catch?(Exception?$e)?{ Db::rollback(); //回滾 }
九、model模型的獲取器
讀取器的命名規(guī)范是:->get + 屬性名的駝峰命名 + Attr
<?php namespace appindexmodel; use thinkModel; class User extends Model { //獲取器:將性別的012修改為男、女、未知 返回 public function getSexAttr($val) { switch ($val) { case 1: return '男'; case 2: return '女'; default: return '未知'; } } //獲取器:格式化時(shí)間戳后返回 public function getUpdateTimeAttr($val){ if(!empty($val)){ //如果是時(shí)間戳,就格式化 if(!strtotime($val)) { return date('Y-m-d H:i:s',$val); }else{ return $val; } }else{ return ''; } } }
補(bǔ)充說明:strtotime()將任何英文文本的日期時(shí)間描述解析為unix 時(shí)間戳,成功則返回時(shí)間戳,否則返回 FALSE(在 PHP 5.1.0之前本函數(shù)在失敗時(shí)返回 -1)
十、model模型的修改器
<?php namespace appindexmodel; use thinkModel; class User extends Model { //修改器 public function setTimeAttr() { return time(); } /** 修改器:對(duì)密碼字段加密之后存儲(chǔ) * $val 第一個(gè)參數(shù)是密碼 * $data 第二個(gè)參數(shù)是添加的數(shù)據(jù)(可選) */ public function setPasswordAttr($val,$data){ if($val === '') { return $val; }else{ return md5($val.$data['email']); } } }
十一、model模型的自動(dòng)完成
auto ? ? ? 新增及更新的時(shí)候,自動(dòng)完成的屬性數(shù)組
insert? ? ?僅新增的時(shí)候,自動(dòng)完成的屬性數(shù)組
update? ?僅更新的時(shí)候,自動(dòng)完成的屬性數(shù)組
1、自動(dòng)完成?
<?php namespace appindexmodel; use thinkModel; class User extends Model { //添加和修改時(shí),都會(huì)自動(dòng)完成的字段 protected $auto = ['addtime']; public function setAddtimeAttr(){ return time(); } }
2、添加數(shù)據(jù)時(shí),自動(dòng)完成?
<?php namespace appindexmodel; use thinkModel; class User extends Model { // 新增 自動(dòng)完成 protected $insert = ['addtime']; public function setAddtimeAttr(){ return time(); } }
3、更新數(shù)據(jù)時(shí),自動(dòng)完成:
<?php namespace appindexmodel; use thinkModel; class User extends Model { // 更新 自動(dòng)完成 protected $update = ['addtime']; public function setAddtimeAttr(){ return time(); } }
十二、自動(dòng)完成時(shí)間戳
在數(shù)據(jù)庫配置文件database.php中,有下列這項(xiàng)配置:
//自動(dòng)寫入時(shí)間戳字段 'auto_timestamp'??=>?false, //如果開啟(設(shè)置為true),則會(huì)自動(dòng)完成所有表的時(shí)間戳,但是不建議這樣,只在需要的地方設(shè)置更安全。
例如對(duì)用戶表的時(shí)間戳自動(dòng)完成,就在User的model中設(shè)置:
<?php namespace appindexmodel; use thinkModel; class User extends Model{ //開啟自動(dòng)完成時(shí)間戳功能 protected $autoWriteTimestamp = true; //開啟后, //添加數(shù)據(jù)時(shí),默認(rèn)自動(dòng)完成的字段是:create_time和update_time //修改數(shù)據(jù)時(shí),默認(rèn)自動(dòng)完成的字段是:update_time //如果數(shù)據(jù)表里不是這兩個(gè)字段,則會(huì)報(bào)錯(cuò)。需要進(jìn)行如下修改: protected $createTime = 'addtime';//修改默認(rèn)的添加時(shí)間字段 protected $updateTime = 'updtime';//修改默認(rèn)的修改時(shí)間字段 protected $updateTime = false;//當(dāng)不需要這個(gè)字段時(shí)設(shè)置為false }
Thinkphp更新時(shí),自動(dòng)更新update_time字段時(shí)間戳的方法:
1、使用update
User::update(['name'=>'安陽'],['id'=>1]);Thinkphp中update方法的源代碼如下:
/** ????*?更新數(shù)據(jù) ????*?@access?public ????*?@param?array??????$data??數(shù)據(jù)數(shù)組 ????*?@param?array??????$where?更新條件 ????*?@param?array|true?$field?允許字段 ????*?@return?$this ????*/ ???public?static?function?update($data?=?[],?$where?=?[],?$field?=?null) ???{ ???????$model?=?new?static(); ???????if?(!empty($field))?{ ???????????$model->allowField($field); ???????} ???????$result?=?$model->isUpdate(true)->save($data,?$where); ???????return?$model; ???}2、使用save
$user=new?User; $user->isUpdate(true)->save(['name'=>'安陽'],['id'=>1]);?
十三、軟刪除
什么是軟刪除?
當(dāng)刪除某些記錄時(shí),有時(shí)我們需要假刪除,只通過修改某個(gè)字段狀態(tài)來標(biāo)記該記錄已刪除,但實(shí)際上,數(shù)據(jù)庫中還是存在這些記錄的。假刪除的應(yīng)用場(chǎng)景還是比較多的,例如支付寶的收款記錄,我們?cè)贏PP上刪除后,就不會(huì)再顯示出來,你是不是以為真的刪掉了,不會(huì)再留下任何痕跡?非也,非也,刪除支付寶收款記錄只是軟刪除,在支付寶的數(shù)據(jù)庫中,實(shí)際上還保留有這些收款記錄,如果你的收款涉嫌違規(guī)或者觸犯法律,警方還是能通過支付寶的網(wǎng)警后臺(tái)查看到的。
1、開啟軟刪除
<?php namespace appindexmodel; use thinkModel; use traitsmodelSoftDelete;//引入軟刪除的類 class Order extends Model{ //使用軟刪除 //刪除時(shí),默認(rèn)更新的字段是delete_time use SoftDelete; //如果數(shù)據(jù)表里不是delete_time這個(gè)字段,則會(huì)報(bào)錯(cuò)。需要進(jìn)行如下修改: protected $deleteTime = 'deltime'; }
2、 控制器里軟刪除,返回影響的行數(shù)
?$res?=?Order::destroy(1);
執(zhí)行刪除后,就會(huì)更新delete_time字段,如果update_time字段也開啟了自動(dòng)完成,也會(huì)更新update_time字段。
3、如果開啟了軟刪除,需要真正地刪除數(shù)據(jù),而不做軟刪除,用下面的方法
//destory()第二個(gè)參數(shù)傳遞true $res?=?Order::destroy(1,true); //delete()參數(shù)傳遞true $orderData?=?Order::get(1); $orderData?->delete(true);
4、查詢已軟刪除的數(shù)據(jù)
$res?=?Order::withTrashed(true)->find(1);
5、查詢僅包含已軟刪除的數(shù)據(jù)
$res?=?Order::onlyTrashed()->select();
推薦學(xué)習(xí):《thinkphp框架》