サマリー:本章通過(guò)對(duì)模型的學(xué)習(xí),對(duì)模型有了進(jìn)一步的了解,了解了模型可以在實(shí)現(xiàn)Db類的基礎(chǔ)上,進(jìn)行更加復(fù)雜的業(yè)務(wù)處理功能。通過(guò)學(xué)習(xí),對(duì)模型進(jìn)行了練習(xí),代碼如下:app\model\User.php<?php namespace app\model; use think\Model; use think\model\concern\SoftDelete; class&n
本章通過(guò)對(duì)模型的學(xué)習(xí),對(duì)模型有了進(jìn)一步的了解,了解了模型可以在實(shí)現(xiàn)Db類的基礎(chǔ)上,進(jìn)行更加復(fù)雜的業(yè)務(wù)處理功能。通過(guò)學(xué)習(xí),對(duì)模型進(jìn)行了練習(xí),代碼如下:
app\model\User.php
<?php namespace app\model; use think\Model; use think\model\concern\SoftDelete; class User extends Model { //引用軟刪除的trait方法集 use SoftDelete; //表名 protected $table='user'; //主鍵 protected $pk='uid'; //設(shè)置刪除時(shí)間字段,供軟刪除使用 protected $deleteTime='delete_time'; //設(shè)置軟刪除默認(rèn)值 protected $defaultSoftDelete=0; }
app\index\controller\User.php:
<?php namespace app\index\controller; use app\model\User as UserModel; use think\Controller; use think\Db; class User extends Controller { public function showMsg() { echo 'uid>20且胸圍大于90,按照胸圍倒序的一條記錄為:'; echo '<br>'; dump($this->getData()); echo '<hr>'; echo 'uid>24的所有數(shù)據(jù)為:'; echo '<br>'; dump($this->getAll(24)); echo '<hr>'; echo '把uid為25的胸圍增加1。'; $this->updateData(25,['weight'=>Db::raw('weight+1')]); echo '<hr>'; echo '新增一行數(shù)據(jù)'; $data=[ 'name'=>'藤森', 'weight'=>95, 'height'=>160 ]; $field=array_keys($data); $this->createData($data,$field); echo '<hr>'; echo '刪除uid為65的數(shù)據(jù)'; echo '<br>'; $this->deleteData(65); echo '<hr>'; echo '已刪除的數(shù)據(jù)為:'; echo '<br>'; dump($this->dataDeleted()); } //獲取uid>20且胸圍大于90,按照胸圍倒序的一條記錄 public function getData() { $res = UserModel::get(function ($query){ $query->field('name,weight,height,delete_time')->where('uid','>',20)->where('weight','>=',90)->order('weight DESC'); }); return $res; } //獲取滿足記錄的所有數(shù)據(jù) public function getAll($uid) { $res = UserModel::all(function ($que) use ($uid){ $que-> field('name,weight,height,delete_time')->where('uid','>',$uid)->order('weight'); }); return $res; } /** * @param $uid 用戶id * @param $arrUpdate 更新數(shù)組條件 * @return UserModel 返回更新的條數(shù) */ public function updateData($uid,$arrUpdate) { $num = UserModel::update( $arrUpdate, function ($query) use ($uid){ $query->where('uid','=',$uid); } ); return $num; } /** * @param $data 添加的數(shù)據(jù)數(shù)組 * @param $field 添加的字段 */ public function createData($data,$field) { UserModel::create($data,$field); } /** * @param $uid 需要?jiǎng)h除的uid */ public function deleteData($uid) { UserModel::destroy($uid); } //顯示已刪除的數(shù)據(jù) public function dataDeleted() { return UserModel::onlyTrashed()->select(); } }
實(shí)現(xiàn)效果圖:
添削の先生:韋小寶添削時(shí)間:2019-02-22 10:55:42
先生のまとめ:寫的很不錯(cuò) 刪除是很重要的 也關(guān)系到安全性 注意條件是必不可少的