批改狀態(tài):未批改
老師批語(yǔ):
public function query() { $staff = StaffModel::get(2); //用閉包來(lái)創(chuàng)建一個(gè)查詢條件 $staff = StaffModel::get(function($query){ $query->where('sex',0)->where('salary','>',4000); //條件 }); echo '性別為男,工資大于等于4000的員工信息'; dump($staff); }
public function query() { StaffModel::where('sex',0) ->where('salary','>',4000) ->find(); dump($staff); }
public function query() { //1. 多條記錄查詢,返回值是多個(gè)數(shù)組/對(duì)象數(shù)組 $staffs = StaffModel::all(function($query){ $query->where('sex',0)->where('salary','>',4000); }); foreach ($staffs as $value) { echo '姓名:'.$value->name.'<br>'; echo '性別:'.$value->sex.'<br>'; echo '年齡:'.$value->age.'<br>'; echo '工資:'.$value->salary.'<hr>'; } // 2. 采用閉包來(lái)實(shí)現(xiàn)將請(qǐng)求變量注入到閉包條件中 //$this->request : 請(qǐng)求對(duì)象 $age = $this->request->param('age') ? : 30; $salary = $this->request->param('salary') ? : 3000; $staff = StaffModel::all(function($query) use($age, $salary) { $query->where('age','<',$age)->where('salary','>',$salary); }); dump($staff); } }
軟刪除的步驟:
1.在數(shù)據(jù)庫(kù)表中添加一個(gè)字段:刪除時(shí)間(刪除標(biāo)志):delete_time
2.在模型類中添加一個(gè)屬性:$deleteTime = 'delete_time';
3.在模型中用use導(dǎo)入軟刪除的trait類庫(kù):SoftDelete
(use think\model\concern\SoftDelete; )
4.最新版支持設(shè)置軟刪除的默認(rèn)字段值($defaultSoftDelete = 0;)
控制器下的 controller/Staff.php文件:
public function delete() { //軟刪除:必須在模型中進(jìn)行配置 //就是在delete_time字段中增加一個(gè)標(biāo)志(時(shí)間戳) public function softDelete() { // StaffModel::destroy(14); //軟刪除的數(shù)據(jù)在普通查詢中不可見(jiàn) // $res = StaffModel::where('salary_id','<',5)->select(); //被軟刪除的數(shù)據(jù)不會(huì)被查詢到(不會(huì)顯示) //如果想在查詢的時(shí)候看到已經(jīng)被刪除的記錄 // $res = StaffModel::withTrashed()->where('salary_id','<',5)->select();//查詢到的數(shù)據(jù)中,被軟刪除的記錄也會(huì)顯示。 //我想查看一下回收站 $res = StaffModel::onlyTrashed()->select(); dump($res); }
模型類中的配置文件:model/staff.php
<?php
namespace app\index\model; use think\Model; //導(dǎo)入thinkphp文件夾下的Model文件 use think\model\concern\SoftDelete; //引入trait方法集 class Staff extends Model //創(chuàng)建一個(gè)staff類,并繼承了Model中所有的功能 { use SoftDelete; //類中引用SoftDelete //設(shè)置數(shù)據(jù)表的名稱 protected $table = 'staff'; //設(shè)置主鍵:默認(rèn)為id protected $pk = 'staff_id'; //設(shè)置刪除時(shí)間的字段名 protected $deleteTime = 'delete_time'; //必須與數(shù)據(jù)庫(kù)表中的delete_time字段一致 //設(shè)置軟刪除字段的默認(rèn)值 protected $defaultSoftDelete = 0; }
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)