abstract:<?php namespace app\index\model; use think\Model; use think\Model\concern\SoftDelete; class Userinfo extends Model{ use SoftDelete; &
<?php namespace app\index\model; use think\Model; use think\Model\concern\SoftDelete; class Userinfo extends Model{ use SoftDelete; protected $table = 'userinfo'; protected $pk = 'id'; protected $deleteTime ='delete_time'; protected $defaultSoftDelete = 0; }
<?php namespace app\index\controller; use think\Controller; use app\index\model\Userinfo; use think\model\concern\SoftDelete; class User extends Controller{ public function instance(Userinfo $userinfo){ // $userinfo = new Userinfo();//实例化模型 dump($userinfo->getName()); $userinfo->name ='欧佳'; $userinfo->sex ='女'; $userinfo->age =26; $userinfo->email ='oj@qq.com'; $userinfo->save(); return '新增成功 id='.$userinfo->id; } //模型查询 public function query (){ //单挑记录 get() $userinfo = Userinfo::get(4); \var_dump($userinfo); //Object echo '<hr>'; echo $userinfo['name']."<br>"; echo $userinfo->name."<br>"; //闭包查询 $userinfo = Userinfo::get(function ($query){ $query -> where ('sex','女'); }); dump($userinfo); echo '<hr>'; //直接静态调用Db类查询构造器 $user = Userinfo::where('sex','=','女') ->find(); dump($user); echo '<hr>'; //多条记录,返回值是多个数组\对象数组 // $users = Userinfo::all(); // dump($users); $users = Userinfo::all(function ($query){ $query->where('sex','=','女'); }); foreach ($users as $user){ echo '姓名'.$user->name.'<br>'; echo '年龄'.$user->age.'<br>'; echo '邮箱'.$user->email.'<br>'; } echo '<hr>'; //采用闭包实现请求变量注入闭包条件中 // $this ->request //请求对象 $sex = $this->request->param('sex')?:'男'; $users = Userinfo::all(function ($query) use ($sex){ $query->where('sex','=',$sex); }); dump($users); } //模型更新 public function update (){ // $userinfo = Userinfo::get(5); // $userinfo->name = '关英'; // $userinfo->sex = '女'; // // $userinfo->save(); // Userinfo::update( // ['name'=>'葛恒玉'], // ['id'=>4] // ); Userinfo::where('name','=','葛恒玉') ->data(['age'=>31]) ->update(); } //模型添加数据 public function add (){ //create方法 $data=[ 'name'=>'李鹏', 'sex'=>'男', 'age'=>'31', 'email'=>'lp@qq.com' ]; // $field = ['name','sex','age','email']; // Userinfo::create($data,$field); Userinfo::insert($data); } //模型删除数据 public function delete (){ // Userinfo::destroy(10); //闭包删除 Userinfo::destroy(function ($query){ $query->where ('status','=',0); }); } //模型软删除数据,必须在模型中配置 public function softDelete (){ // Userinfo::destroy(14); $res = Userinfo::where('id','>',0)->select(); dump($res); //查看被软删除过的数据 $res = Userinfo::onlyTrashed()->select(); dump($res); } }
Correcting teacher:查无此人Correction time:2019-05-09 14:10:28
Teacher's summary:完成的不错。数据库最常用的操作,就是增删查改,不过删除是最少用的。继续加油。