thinkPHP5.1之模型獲取器,修改器,自動更新,填充等等
文件位置
<?php namespace app\index\model; use think\Model; use think\model\concern\SoftDelete; //導入軟刪除功能 class Staff extends Model { use SoftDelete; protected $table = 'aaa'; protected $pk = 'id'; //設置刪除時間字段,配合軟刪除功能 protected $deleteTime = 'delete_time'; //設置軟刪除字段的默認值 protected $defaultSoftDelete = 0; // 模型獲取器 // 獲取器 1.sex protected function getSexAttr($value) { $sex = [0=>'男',1=>'女']; return $sex[$value]; } // 獲取器 2.money protected function getMoneyAttr($value,$data) { return $data['name'].'的工資是:'.$value; } // 獲取器 3.abc(自定義) protected function getAbcAttr($value,$data) { return $data['name'].'的年齡是:'.$data['age'].' ,工資是:'.$data['money']; } // 模型修改器 // 模型獲取器 1.時間轉換為時間戳 protected function setEntryTimeAttr($value) { return strtotime($value); } // 模型獲取器 2.支持第二個參數(shù) protected function setMoneyAttr($value,$data) { return $value + $data['age']; } //類型轉換 protected $type=[ 'id' => 'interger', 'sex' => 'interger', 'money' => 'interger', 'age' => 'interger', ]; //自動完成 針對寫操作.新增\更新 //相當于設置的默認值 protected $insert = [ 'sex' => 0, 'age' => 18, 'money' => 3600 ]; //更新 protected $update = ['sex' => 0]; //針對新增與更新 更新一些相同的東西 protected $auto = ['sex' => 0]; //開始當前時間戳 功能 // (也可以在config/database.PHP中開啟) protected $autoWriteTimestamp = true; //設置更新的字段 protected $createTime = 'create_time'; protected $updateTime = 'update_time'; }
點擊 "運行實例" 按鈕查看在線實例
<?php //cmd 創(chuàng)建模型 php think make:model index/Staff namespace app\index\controller; /** * 使用模型獲取器 */ use think\Controller; use app\index\model\Staff as Zhang; class Dome4 extends Controller { //http://tp.io/Index.php/index/Dome4/get //模型獲取器 function get() { $res = Zhang::get(40); dump($res->sex); dump($res->money); dump($res->abc); } //模型修改取器 function set() { $res = Zhang::get(41); $res->age=20; $res->entry_time='2015-06-23'; $res->money='1000'; $res->save(); } //自動更新時間戳功能 function auto() { Zhang::update(['name'=>'老鼠愛小貓'],['id'=>63]); } }
點擊 "運行實例" 按鈕查看在線實例
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號