abstract:本章通过对模型的学习,对模型有了进一步的了解,了解了模型可以在实现Db类的基础上,进行更加复杂的业务处理功能。通过学习,对模型进行了练习,代码如下:app\model\User.php<?php namespace app\model; use think\Model; use think\model\concern\SoftDelete; class&n
本章通过对模型的学习,对模型有了进一步的了解,了解了模型可以在实现Db类的基础上,进行更加复杂的业务处理功能。通过学习,对模型进行了练习,代码如下:
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'; //设置删除时间字段,供软删除使用 protected $deleteTime='delete_time'; //设置软删除默认值 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的所有数据为:'; echo '<br>'; dump($this->getAll(24)); echo '<hr>'; echo '把uid为25的胸围增加1。'; $this->updateData(25,['weight'=>Db::raw('weight+1')]); echo '<hr>'; echo '新增一行数据'; $data=[ 'name'=>'藤森', 'weight'=>95, 'height'=>160 ]; $field=array_keys($data); $this->createData($data,$field); echo '<hr>'; echo '删除uid为65的数据'; echo '<br>'; $this->deleteData(65); echo '<hr>'; echo '已删除的数据为:'; 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; } //获取满足记录的所有数据 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 更新数组条件 * @return UserModel 返回更新的条数 */ public function updateData($uid,$arrUpdate) { $num = UserModel::update( $arrUpdate, function ($query) use ($uid){ $query->where('uid','=',$uid); } ); return $num; } /** * @param $data 添加的数据数组 * @param $field 添加的字段 */ public function createData($data,$field) { UserModel::create($data,$field); } /** * @param $uid 需要删除的uid */ public function deleteData($uid) { UserModel::destroy($uid); } //显示已删除的数据 public function dataDeleted() { return UserModel::onlyTrashed()->select(); } }
实现效果图:
Correcting teacher:韦小宝Correction time:2019-02-22 10:55:42
Teacher's summary:写的很不错 删除是很重要的 也关系到安全性 注意条件是必不可少的