Model.php 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think;
  12. use BadMethodCallException;
  13. use InvalidArgumentException;
  14. use think\db\Query;
  15. use think\exception\ValidateException;
  16. use think\model\Collection as ModelCollection;
  17. use think\model\Relation;
  18. use think\model\relation\BelongsTo;
  19. use think\model\relation\BelongsToMany;
  20. use think\model\relation\HasMany;
  21. use think\model\relation\HasManyThrough;
  22. use think\model\relation\HasOne;
  23. use think\model\relation\MorphMany;
  24. use think\model\relation\MorphOne;
  25. use think\model\relation\MorphTo;
  26. /**
  27. * Class Model
  28. * @package think
  29. * @mixin Query
  30. */
  31. abstract class Model implements \JsonSerializable, \ArrayAccess
  32. {
  33. // 数据库查询对象池
  34. protected static $links = [];
  35. // 数据库配置
  36. protected $connection = [];
  37. // 父关联模型对象
  38. protected $parent;
  39. // 数据库查询对象
  40. protected $query;
  41. // 当前模型名称
  42. protected $name;
  43. // 数据表名称
  44. protected $table;
  45. // 当前类名称
  46. protected $class;
  47. // 回调事件
  48. private static $event = [];
  49. // 错误信息
  50. protected $error;
  51. // 字段验证规则
  52. protected $validate;
  53. // 数据表主键 复合主键使用数组定义 不设置则自动获取
  54. protected $pk;
  55. // 数据表字段信息 留空则自动获取
  56. protected $field = [];
  57. // 数据排除字段
  58. protected $except = [];
  59. // 数据废弃字段
  60. protected $disuse = [];
  61. // 只读字段
  62. protected $readonly = [];
  63. // 显示属性
  64. protected $visible = [];
  65. // 隐藏属性
  66. protected $hidden = [];
  67. // 追加属性
  68. protected $append = [];
  69. // 数据信息
  70. protected $data = [];
  71. // 原始数据
  72. protected $origin = [];
  73. // 关联模型
  74. protected $relation = [];
  75. // 保存自动完成列表
  76. protected $auto = [];
  77. // 新增自动完成列表
  78. protected $insert = [];
  79. // 更新自动完成列表
  80. protected $update = [];
  81. // 是否需要自动写入时间戳 如果设置为字符串 则表示时间字段的类型
  82. protected $autoWriteTimestamp;
  83. // 创建时间字段
  84. protected $createTime = 'create_time';
  85. // 更新时间字段
  86. protected $updateTime = 'update_time';
  87. // 时间字段取出后的默认时间格式
  88. protected $dateFormat;
  89. // 字段类型或者格式转换
  90. protected $type = [];
  91. // 是否为更新数据
  92. protected $isUpdate = false;
  93. // 是否强制更新所有数据
  94. protected $force = false;
  95. // 更新条件
  96. protected $updateWhere;
  97. // 验证失败是否抛出异常
  98. protected $failException = false;
  99. // 全局查询范围
  100. protected $useGlobalScope = true;
  101. // 是否采用批量验证
  102. protected $batchValidate = false;
  103. // 查询数据集对象
  104. protected $resultSetType;
  105. // 关联自动写入
  106. protected $relationWrite;
  107. /**
  108. * 初始化过的模型.
  109. *
  110. * @var array
  111. */
  112. protected static $initialized = [];
  113. /**
  114. * 构造方法
  115. * @access public
  116. * @param array|object $data 数据
  117. */
  118. public function __construct($data = [])
  119. {
  120. if (is_object($data)) {
  121. $this->data = get_object_vars($data);
  122. } else {
  123. $this->data = $data;
  124. }
  125. if ($this->disuse) {
  126. // 废弃字段
  127. foreach ((array) $this->disuse as $key) {
  128. if (array_key_exists($key, $this->data)) {
  129. unset($this->data[$key]);
  130. }
  131. }
  132. }
  133. // 记录原始数据
  134. $this->origin = $this->data;
  135. // 当前类名
  136. $this->class = get_called_class();
  137. if (empty($this->name)) {
  138. // 当前模型名
  139. $name = str_replace('\\', '/', $this->class);
  140. $this->name = basename($name);
  141. if (Config::get('class_suffix')) {
  142. $suffix = basename(dirname($name));
  143. $this->name = substr($this->name, 0, -strlen($suffix));
  144. }
  145. }
  146. if (is_null($this->autoWriteTimestamp)) {
  147. // 自动写入时间戳
  148. $this->autoWriteTimestamp = $this->getQuery()->getConfig('auto_timestamp');
  149. }
  150. if (is_null($this->dateFormat)) {
  151. // 设置时间戳格式
  152. $this->dateFormat = $this->getQuery()->getConfig('datetime_format');
  153. }
  154. if (is_null($this->resultSetType)) {
  155. $this->resultSetType = $this->getQuery()->getConfig('resultset_type');
  156. }
  157. // 执行初始化操作
  158. $this->initialize();
  159. }
  160. /**
  161. * 创建模型的查询对象
  162. * @access protected
  163. * @return Query
  164. */
  165. protected function buildQuery()
  166. {
  167. // 合并数据库配置
  168. if (!empty($this->connection)) {
  169. if (is_array($this->connection)) {
  170. $connection = array_merge(Config::get('database'), $this->connection);
  171. } else {
  172. $connection = $this->connection;
  173. }
  174. } else {
  175. $connection = [];
  176. }
  177. $con = Db::connect($connection);
  178. // 设置当前模型 确保查询返回模型对象
  179. $queryClass = $this->query ?: $con->getConfig('query');
  180. $query = new $queryClass($con, $this);
  181. // 设置当前数据表和模型名
  182. if (!empty($this->table)) {
  183. $query->setTable($this->table);
  184. } else {
  185. $query->name($this->name);
  186. }
  187. if (!empty($this->pk)) {
  188. $query->pk($this->pk);
  189. }
  190. return $query;
  191. }
  192. /**
  193. * 创建新的模型实例
  194. * @access public
  195. * @param array|object $data 数据
  196. * @param bool $isUpdate 是否为更新
  197. * @param mixed $where 更新条件
  198. * @return Model
  199. */
  200. public function newInstance($data = [], $isUpdate = false, $where = null)
  201. {
  202. return (new static($data))->isUpdate($isUpdate, $where);
  203. }
  204. /**
  205. * 获取当前模型的查询对象
  206. * @access public
  207. * @param bool $buildNewQuery 创建新的查询对象
  208. * @return Query
  209. */
  210. public function getQuery($buildNewQuery = false)
  211. {
  212. if ($buildNewQuery) {
  213. return $this->buildQuery();
  214. } elseif (!isset(self::$links[$this->class])) {
  215. // 创建模型查询对象
  216. self::$links[$this->class] = $this->buildQuery();
  217. }
  218. return self::$links[$this->class];
  219. }
  220. /**
  221. * 获取当前模型的数据库查询对象
  222. * @access public
  223. * @param bool $useBaseQuery 是否调用全局查询范围
  224. * @param bool $buildNewQuery 创建新的查询对象
  225. * @return Query
  226. */
  227. public function db($useBaseQuery = true, $buildNewQuery = true)
  228. {
  229. $query = $this->getQuery($buildNewQuery);
  230. // 全局作用域
  231. if ($useBaseQuery && method_exists($this, 'base')) {
  232. call_user_func_array([$this, 'base'], [ & $query]);
  233. }
  234. // 返回当前模型的数据库查询对象
  235. return $query;
  236. }
  237. /**
  238. * 初始化模型
  239. * @access protected
  240. * @return void
  241. */
  242. protected function initialize()
  243. {
  244. $class = get_class($this);
  245. if (!isset(static::$initialized[$class])) {
  246. static::$initialized[$class] = true;
  247. static::init();
  248. }
  249. }
  250. /**
  251. * 初始化处理
  252. * @access protected
  253. * @return void
  254. */
  255. protected static function init()
  256. {
  257. }
  258. /**
  259. * 设置父关联对象
  260. * @access public
  261. * @param Model $model 模型对象
  262. * @return $this
  263. */
  264. public function setParent($model)
  265. {
  266. $this->parent = $model;
  267. return $this;
  268. }
  269. /**
  270. * 获取父关联对象
  271. * @access public
  272. * @return Model
  273. */
  274. public function getParent()
  275. {
  276. return $this->parent;
  277. }
  278. /**
  279. * 设置数据对象值
  280. * @access public
  281. * @param mixed $data 数据或者属性名
  282. * @param mixed $value 值
  283. * @return $this
  284. */
  285. public function data($data, $value = null)
  286. {
  287. if (is_string($data)) {
  288. $this->data[$data] = $value;
  289. } else {
  290. // 清空数据
  291. $this->data = [];
  292. if (is_object($data)) {
  293. $data = get_object_vars($data);
  294. }
  295. if (true === $value) {
  296. // 数据对象赋值
  297. foreach ($data as $key => $value) {
  298. $this->setAttr($key, $value, $data);
  299. }
  300. } else {
  301. $this->data = $data;
  302. }
  303. }
  304. return $this;
  305. }
  306. /**
  307. * 获取对象原始数据 如果不存在指定字段返回false
  308. * @access public
  309. * @param string $name 字段名 留空获取全部
  310. * @return mixed
  311. * @throws InvalidArgumentException
  312. */
  313. public function getData($name = null)
  314. {
  315. if (is_null($name)) {
  316. return $this->data;
  317. } elseif (array_key_exists($name, $this->data)) {
  318. return $this->data[$name];
  319. } elseif (array_key_exists($name, $this->relation)) {
  320. return $this->relation[$name];
  321. } else {
  322. throw new InvalidArgumentException('property not exists:' . $this->class . '->' . $name);
  323. }
  324. }
  325. /**
  326. * 是否需要自动写入时间字段
  327. * @access public
  328. * @param bool $auto
  329. * @return $this
  330. */
  331. public function isAutoWriteTimestamp($auto)
  332. {
  333. $this->autoWriteTimestamp = $auto;
  334. return $this;
  335. }
  336. /**
  337. * 更新是否强制写入数据 而不做比较
  338. * @access public
  339. * @param bool $force
  340. * @return $this
  341. */
  342. public function force($force = true)
  343. {
  344. $this->force = $force;
  345. return $this;
  346. }
  347. /**
  348. * 修改器 设置数据对象值
  349. * @access public
  350. * @param string $name 属性名
  351. * @param mixed $value 属性值
  352. * @param array $data 数据
  353. * @return $this
  354. */
  355. public function setAttr($name, $value, $data = [])
  356. {
  357. if (is_null($value) && $this->autoWriteTimestamp && in_array($name, [$this->createTime, $this->updateTime])) {
  358. // 自动写入的时间戳字段
  359. $value = $this->autoWriteTimestamp($name);
  360. } else {
  361. // 检测修改器
  362. $method = 'set' . Loader::parseName($name, 1) . 'Attr';
  363. if (method_exists($this, $method)) {
  364. $value = $this->$method($value, array_merge($this->data, $data), $this->relation);
  365. } elseif (isset($this->type[$name])) {
  366. // 类型转换
  367. $value = $this->writeTransform($value, $this->type[$name]);
  368. }
  369. }
  370. // 设置数据对象属性
  371. $this->data[$name] = $value;
  372. return $this;
  373. }
  374. /**
  375. * 获取当前模型的关联模型数据
  376. * @access public
  377. * @param string $name 关联方法名
  378. * @return mixed
  379. */
  380. public function getRelation($name = null)
  381. {
  382. if (is_null($name)) {
  383. return $this->relation;
  384. } elseif (array_key_exists($name, $this->relation)) {
  385. return $this->relation[$name];
  386. } else {
  387. return;
  388. }
  389. }
  390. /**
  391. * 设置关联数据对象值
  392. * @access public
  393. * @param string $name 属性名
  394. * @param mixed $value 属性值
  395. * @return $this
  396. */
  397. public function setRelation($name, $value)
  398. {
  399. $this->relation[$name] = $value;
  400. return $this;
  401. }
  402. /**
  403. * 自动写入时间戳
  404. * @access public
  405. * @param string $name 时间戳字段
  406. * @return mixed
  407. */
  408. protected function autoWriteTimestamp($name)
  409. {
  410. if (isset($this->type[$name])) {
  411. $type = $this->type[$name];
  412. if (strpos($type, ':')) {
  413. list($type, $param) = explode(':', $type, 2);
  414. }
  415. switch ($type) {
  416. case 'datetime':
  417. case 'date':
  418. $format = !empty($param) ? $param : $this->dateFormat;
  419. $value = $this->formatDateTime(time(), $format);
  420. break;
  421. case 'timestamp':
  422. case 'integer':
  423. default:
  424. $value = time();
  425. break;
  426. }
  427. } elseif (is_string($this->autoWriteTimestamp) && in_array(strtolower($this->autoWriteTimestamp), [
  428. 'datetime',
  429. 'date',
  430. 'timestamp',
  431. ])
  432. ) {
  433. $value = $this->formatDateTime(time(), $this->dateFormat);
  434. } else {
  435. $value = $this->formatDateTime(time(), $this->dateFormat, true);
  436. }
  437. return $value;
  438. }
  439. /**
  440. * 时间日期字段格式化处理
  441. * @access public
  442. * @param mixed $time 时间日期表达式
  443. * @param mixed $format 日期格式
  444. * @param bool $timestamp 是否进行时间戳转换
  445. * @return mixed
  446. */
  447. protected function formatDateTime($time, $format, $timestamp = false)
  448. {
  449. if (false !== strpos($format, '\\')) {
  450. $time = new $format($time);
  451. } elseif (!$timestamp && false !== $format) {
  452. $time = date($format, $time);
  453. }
  454. return $time;
  455. }
  456. /**
  457. * 数据写入 类型转换
  458. * @access public
  459. * @param mixed $value 值
  460. * @param string|array $type 要转换的类型
  461. * @return mixed
  462. */
  463. protected function writeTransform($value, $type)
  464. {
  465. if (is_null($value)) {
  466. return;
  467. }
  468. if (is_array($type)) {
  469. list($type, $param) = $type;
  470. } elseif (strpos($type, ':')) {
  471. list($type, $param) = explode(':', $type, 2);
  472. }
  473. switch ($type) {
  474. case 'integer':
  475. $value = (int) $value;
  476. break;
  477. case 'float':
  478. if (empty($param)) {
  479. $value = (float) $value;
  480. } else {
  481. $value = (float) number_format($value, $param, '.', '');
  482. }
  483. break;
  484. case 'boolean':
  485. $value = (bool) $value;
  486. break;
  487. case 'timestamp':
  488. if (!is_numeric($value)) {
  489. $value = strtotime($value);
  490. }
  491. break;
  492. case 'datetime':
  493. $format = !empty($param) ? $param : $this->dateFormat;
  494. $value = is_numeric($value) ? $value : strtotime($value);
  495. $value = $this->formatDateTime($value, $format);
  496. break;
  497. case 'object':
  498. if (is_object($value)) {
  499. $value = json_encode($value, JSON_FORCE_OBJECT);
  500. }
  501. break;
  502. case 'array':
  503. $value = (array) $value;
  504. case 'json':
  505. $option = !empty($param) ? (int) $param : JSON_UNESCAPED_UNICODE;
  506. $value = json_encode($value, $option);
  507. break;
  508. case 'serialize':
  509. $value = serialize($value);
  510. break;
  511. }
  512. return $value;
  513. }
  514. /**
  515. * 获取器 获取数据对象的值
  516. * @access public
  517. * @param string $name 名称
  518. * @return mixed
  519. * @throws InvalidArgumentException
  520. */
  521. public function getAttr($name)
  522. {
  523. try {
  524. $notFound = false;
  525. $value = $this->getData($name);
  526. } catch (InvalidArgumentException $e) {
  527. $notFound = true;
  528. $value = null;
  529. }
  530. // 检测属性获取器
  531. $method = 'get' . Loader::parseName($name, 1) . 'Attr';
  532. if (method_exists($this, $method)) {
  533. $value = $this->$method($value, $this->data, $this->relation);
  534. } elseif (isset($this->type[$name])) {
  535. // 类型转换
  536. $value = $this->readTransform($value, $this->type[$name]);
  537. } elseif (in_array($name, [$this->createTime, $this->updateTime])) {
  538. if (is_string($this->autoWriteTimestamp) && in_array(strtolower($this->autoWriteTimestamp), [
  539. 'datetime',
  540. 'date',
  541. 'timestamp',
  542. ])
  543. ) {
  544. $value = $this->formatDateTime(strtotime($value), $this->dateFormat);
  545. } else {
  546. $value = $this->formatDateTime($value, $this->dateFormat);
  547. }
  548. } elseif ($notFound) {
  549. $relation = Loader::parseName($name, 1, false);
  550. if (method_exists($this, $relation)) {
  551. $modelRelation = $this->$relation();
  552. // 不存在该字段 获取关联数据
  553. $value = $this->getRelationData($modelRelation);
  554. // 保存关联对象值
  555. $this->relation[$name] = $value;
  556. } else {
  557. throw new InvalidArgumentException('property not exists:' . $this->class . '->' . $name);
  558. }
  559. }
  560. return $value;
  561. }
  562. /**
  563. * 获取关联模型数据
  564. * @access public
  565. * @param Relation $modelRelation 模型关联对象
  566. * @return mixed
  567. * @throws BadMethodCallException
  568. */
  569. protected function getRelationData(Relation $modelRelation)
  570. {
  571. if ($this->parent && !$modelRelation->isSelfRelation() && get_class($modelRelation->getModel()) == get_class($this->parent)) {
  572. $value = $this->parent;
  573. } else {
  574. // 首先获取关联数据
  575. if (method_exists($modelRelation, 'getRelation')) {
  576. $value = $modelRelation->getRelation();
  577. } else {
  578. throw new BadMethodCallException('method not exists:' . get_class($modelRelation) . '-> getRelation');
  579. }
  580. }
  581. return $value;
  582. }
  583. /**
  584. * 数据读取 类型转换
  585. * @access public
  586. * @param mixed $value 值
  587. * @param string|array $type 要转换的类型
  588. * @return mixed
  589. */
  590. protected function readTransform($value, $type)
  591. {
  592. if (is_null($value)) {
  593. return;
  594. }
  595. if (is_array($type)) {
  596. list($type, $param) = $type;
  597. } elseif (strpos($type, ':')) {
  598. list($type, $param) = explode(':', $type, 2);
  599. }
  600. switch ($type) {
  601. case 'integer':
  602. $value = (int) $value;
  603. break;
  604. case 'float':
  605. if (empty($param)) {
  606. $value = (float) $value;
  607. } else {
  608. $value = (float) number_format($value, $param, '.', '');
  609. }
  610. break;
  611. case 'boolean':
  612. $value = (bool) $value;
  613. break;
  614. case 'timestamp':
  615. if (!is_null($value)) {
  616. $format = !empty($param) ? $param : $this->dateFormat;
  617. $value = $this->formatDateTime($value, $format);
  618. }
  619. break;
  620. case 'datetime':
  621. if (!is_null($value)) {
  622. $format = !empty($param) ? $param : $this->dateFormat;
  623. $value = $this->formatDateTime(strtotime($value), $format);
  624. }
  625. break;
  626. case 'json':
  627. $value = json_decode($value, true);
  628. break;
  629. case 'array':
  630. $value = empty($value) ? [] : json_decode($value, true);
  631. break;
  632. case 'object':
  633. $value = empty($value) ? new \stdClass() : json_decode($value);
  634. break;
  635. case 'serialize':
  636. try {
  637. $value = unserialize($value);
  638. } catch (\Exception $e) {
  639. $value = null;
  640. }
  641. break;
  642. default:
  643. if (false !== strpos($type, '\\')) {
  644. // 对象类型
  645. $value = new $type($value);
  646. }
  647. }
  648. return $value;
  649. }
  650. /**
  651. * 设置需要追加的输出属性
  652. * @access public
  653. * @param array $append 属性列表
  654. * @param bool $override 是否覆盖
  655. * @return $this
  656. */
  657. public function append($append = [], $override = false)
  658. {
  659. $this->append = $override ? $append : array_merge($this->append, $append);
  660. return $this;
  661. }
  662. /**
  663. * 设置附加关联对象的属性
  664. * @access public
  665. * @param string $relation 关联方法
  666. * @param string|array $append 追加属性名
  667. * @return $this
  668. * @throws Exception
  669. */
  670. public function appendRelationAttr($relation, $append)
  671. {
  672. if (is_string($append)) {
  673. $append = explode(',', $append);
  674. }
  675. $relation = Loader::parseName($relation, 1, false);
  676. // 获取关联数据
  677. if (isset($this->relation[$relation])) {
  678. $model = $this->relation[$relation];
  679. } else {
  680. $model = $this->getRelationData($this->$relation());
  681. }
  682. if ($model instanceof Model) {
  683. foreach ($append as $key => $attr) {
  684. $key = is_numeric($key) ? $attr : $key;
  685. if (isset($this->data[$key])) {
  686. throw new Exception('bind attr has exists:' . $key);
  687. } else {
  688. $this->data[$key] = $model->getAttr($attr);
  689. }
  690. }
  691. }
  692. return $this;
  693. }
  694. /**
  695. * 设置需要隐藏的输出属性
  696. * @access public
  697. * @param array $hidden 属性列表
  698. * @param bool $override 是否覆盖
  699. * @return $this
  700. */
  701. public function hidden($hidden = [], $override = false)
  702. {
  703. $this->hidden = $override ? $hidden : array_merge($this->hidden, $hidden);
  704. return $this;
  705. }
  706. /**
  707. * 设置需要输出的属性
  708. * @access public
  709. * @param array $visible
  710. * @param bool $override 是否覆盖
  711. * @return $this
  712. */
  713. public function visible($visible = [], $override = false)
  714. {
  715. $this->visible = $override ? $visible : array_merge($this->visible, $visible);
  716. return $this;
  717. }
  718. /**
  719. * 解析隐藏及显示属性
  720. * @access protected
  721. * @param array $attrs 属性
  722. * @param array $result 结果集
  723. * @param bool $visible
  724. * @return array
  725. */
  726. protected function parseAttr($attrs, &$result, $visible = true)
  727. {
  728. $array = [];
  729. foreach ($attrs as $key => $val) {
  730. if (is_array($val)) {
  731. if ($visible) {
  732. $array[] = $key;
  733. }
  734. $result[$key] = $val;
  735. } elseif (strpos($val, '.')) {
  736. list($key, $name) = explode('.', $val);
  737. if ($visible) {
  738. $array[] = $key;
  739. }
  740. $result[$key][] = $name;
  741. } else {
  742. $array[] = $val;
  743. }
  744. }
  745. return $array;
  746. }
  747. /**
  748. * 转换子模型对象
  749. * @access protected
  750. * @param Model|ModelCollection $model
  751. * @param $visible
  752. * @param $hidden
  753. * @param $key
  754. * @return array
  755. */
  756. protected function subToArray($model, $visible, $hidden, $key)
  757. {
  758. // 关联模型对象
  759. if (isset($visible[$key])) {
  760. $model->visible($visible[$key]);
  761. } elseif (isset($hidden[$key])) {
  762. $model->hidden($hidden[$key]);
  763. }
  764. return $model->toArray();
  765. }
  766. /**
  767. * 转换当前模型对象为数组
  768. * @access public
  769. * @return array
  770. */
  771. public function toArray()
  772. {
  773. $item = [];
  774. $visible = [];
  775. $hidden = [];
  776. $data = array_merge($this->data, $this->relation);
  777. // 过滤属性
  778. if (!empty($this->visible)) {
  779. $array = $this->parseAttr($this->visible, $visible);
  780. $data = array_intersect_key($data, array_flip($array));
  781. } elseif (!empty($this->hidden)) {
  782. $array = $this->parseAttr($this->hidden, $hidden, false);
  783. $data = array_diff_key($data, array_flip($array));
  784. }
  785. foreach ($data as $key => $val) {
  786. if ($val instanceof Model || $val instanceof ModelCollection) {
  787. // 关联模型对象
  788. $item[$key] = $this->subToArray($val, $visible, $hidden, $key);
  789. } elseif (is_array($val) && reset($val) instanceof Model) {
  790. // 关联模型数据集
  791. $arr = [];
  792. foreach ($val as $k => $value) {
  793. $arr[$k] = $this->subToArray($value, $visible, $hidden, $key);
  794. }
  795. $item[$key] = $arr;
  796. } else {
  797. // 模型属性
  798. $item[$key] = $this->getAttr($key);
  799. }
  800. }
  801. // 追加属性(必须定义获取器)
  802. if (!empty($this->append)) {
  803. foreach ($this->append as $key => $name) {
  804. if (is_array($name)) {
  805. // 追加关联对象属性
  806. $relation = $this->getAttr($key);
  807. $item[$key] = $relation->append($name)->toArray();
  808. } elseif (strpos($name, '.')) {
  809. list($key, $attr) = explode('.', $name);
  810. // 追加关联对象属性
  811. $relation = $this->getAttr($key);
  812. $item[$key] = $relation->append([$attr])->toArray();
  813. } else {
  814. $relation = Loader::parseName($name, 1, false);
  815. if (method_exists($this, $relation)) {
  816. $modelRelation = $this->$relation();
  817. $value = $this->getRelationData($modelRelation);
  818. if (method_exists($modelRelation, 'getBindAttr')) {
  819. $bindAttr = $modelRelation->getBindAttr();
  820. if ($bindAttr) {
  821. foreach ($bindAttr as $key => $attr) {
  822. $key = is_numeric($key) ? $attr : $key;
  823. if (isset($this->data[$key])) {
  824. throw new Exception('bind attr has exists:' . $key);
  825. } else {
  826. $item[$key] = $value ? $value->getAttr($attr) : null;
  827. }
  828. }
  829. continue;
  830. }
  831. }
  832. $item[$name] = $value;
  833. } else {
  834. $item[$name] = $this->getAttr($name);
  835. }
  836. }
  837. }
  838. }
  839. return !empty($item) ? $item : [];
  840. }
  841. /**
  842. * 转换当前模型对象为JSON字符串
  843. * @access public
  844. * @param integer $options json参数
  845. * @return string
  846. */
  847. public function toJson($options = JSON_UNESCAPED_UNICODE)
  848. {
  849. return json_encode($this->toArray(), $options);
  850. }
  851. /**
  852. * 移除当前模型的关联属性
  853. * @access public
  854. * @return $this
  855. */
  856. public function removeRelation()
  857. {
  858. $this->relation = [];
  859. return $this;
  860. }
  861. /**
  862. * 转换当前模型数据集为数据集对象
  863. * @access public
  864. * @param array|\think\Collection $collection 数据集
  865. * @return \think\Collection
  866. */
  867. public function toCollection($collection)
  868. {
  869. if ($this->resultSetType) {
  870. if ('collection' == $this->resultSetType) {
  871. $collection = new ModelCollection($collection);
  872. } elseif (false !== strpos($this->resultSetType, '\\')) {
  873. $class = $this->resultSetType;
  874. $collection = new $class($collection);
  875. }
  876. }
  877. return $collection;
  878. }
  879. /**
  880. * 关联数据一起更新
  881. * @access public
  882. * @param mixed $relation 关联
  883. * @return $this
  884. */
  885. public function together($relation)
  886. {
  887. if (is_string($relation)) {
  888. $relation = explode(',', $relation);
  889. }
  890. $this->relationWrite = $relation;
  891. return $this;
  892. }
  893. /**
  894. * 获取模型对象的主键
  895. * @access public
  896. * @param string $name 模型名
  897. * @return mixed
  898. */
  899. public function getPk($name = '')
  900. {
  901. if (!empty($name)) {
  902. $table = $this->getQuery()->getTable($name);
  903. return $this->getQuery()->getPk($table);
  904. } elseif (empty($this->pk)) {
  905. $this->pk = $this->getQuery()->getPk();
  906. }
  907. return $this->pk;
  908. }
  909. /**
  910. * 判断一个字段名是否为主键字段
  911. * @access public
  912. * @param string $key 名称
  913. * @return bool
  914. */
  915. protected function isPk($key)
  916. {
  917. $pk = $this->getPk();
  918. if (is_string($pk) && $pk == $key) {
  919. return true;
  920. } elseif (is_array($pk) && in_array($key, $pk)) {
  921. return true;
  922. }
  923. return false;
  924. }
  925. /**
  926. * 保存当前数据对象
  927. * @access public
  928. * @param array $data 数据
  929. * @param array $where 更新条件
  930. * @param string $sequence 自增序列名
  931. * @return integer|false
  932. */
  933. public function save($data = [], $where = [], $sequence = null)
  934. {
  935. if (is_string($data)) {
  936. $sequence = $data;
  937. $data = [];
  938. }
  939. if (!empty($data)) {
  940. // 数据自动验证
  941. if (!$this->validateData($data)) {
  942. return false;
  943. }
  944. // 数据对象赋值
  945. foreach ($data as $key => $value) {
  946. $this->setAttr($key, $value, $data);
  947. }
  948. if (!empty($where)) {
  949. $this->isUpdate = true;
  950. $this->updateWhere = $where;
  951. }
  952. }
  953. // 自动关联写入
  954. if (!empty($this->relationWrite)) {
  955. $relation = [];
  956. foreach ($this->relationWrite as $key => $name) {
  957. if (is_array($name)) {
  958. if (key($name) === 0) {
  959. $relation[$key] = [];
  960. foreach ($name as $val) {
  961. if (isset($this->data[$val])) {
  962. $relation[$key][$val] = $this->data[$val];
  963. unset($this->data[$val]);
  964. }
  965. }
  966. } else {
  967. $relation[$key] = $name;
  968. }
  969. } elseif (isset($this->relation[$name])) {
  970. $relation[$name] = $this->relation[$name];
  971. } elseif (isset($this->data[$name])) {
  972. $relation[$name] = $this->data[$name];
  973. unset($this->data[$name]);
  974. }
  975. }
  976. }
  977. // 数据自动完成
  978. $this->autoCompleteData($this->auto);
  979. // 事件回调
  980. if (false === $this->trigger('before_write', $this)) {
  981. return false;
  982. }
  983. $pk = $this->getPk();
  984. if ($this->isUpdate) {
  985. // 自动更新
  986. $this->autoCompleteData($this->update);
  987. // 事件回调
  988. if (false === $this->trigger('before_update', $this)) {
  989. return false;
  990. }
  991. // 获取有更新的数据
  992. $data = $this->getChangedData();
  993. if (empty($data) || (count($data) == 1 && is_string($pk) && isset($data[$pk]))) {
  994. // 关联更新
  995. if (isset($relation)) {
  996. $this->autoRelationUpdate($relation);
  997. }
  998. return 0;
  999. } elseif ($this->autoWriteTimestamp && $this->updateTime && !isset($data[$this->updateTime])) {
  1000. // 自动写入更新时间
  1001. $data[$this->updateTime] = $this->autoWriteTimestamp($this->updateTime);
  1002. $this->data[$this->updateTime] = $data[$this->updateTime];
  1003. }
  1004. if (empty($where) && !empty($this->updateWhere)) {
  1005. $where = $this->updateWhere;
  1006. }
  1007. // 保留主键数据
  1008. foreach ($this->data as $key => $val) {
  1009. if ($this->isPk($key)) {
  1010. $data[$key] = $val;
  1011. }
  1012. }
  1013. $array = [];
  1014. foreach ((array) $pk as $key) {
  1015. if (isset($data[$key])) {
  1016. $array[$key] = $data[$key];
  1017. unset($data[$key]);
  1018. }
  1019. }
  1020. if (!empty($array)) {
  1021. $where = $array;
  1022. }
  1023. // 检测字段
  1024. $allowFields = $this->checkAllowField(array_merge($this->auto, $this->update));
  1025. // 模型更新
  1026. if (!empty($allowFields)) {
  1027. $result = $this->getQuery()->where($where)->strict(false)->field($allowFields)->update($data);
  1028. } else {
  1029. $result = $this->getQuery()->where($where)->update($data);
  1030. }
  1031. // 关联更新
  1032. if (isset($relation)) {
  1033. $this->autoRelationUpdate($relation);
  1034. }
  1035. // 更新回调
  1036. $this->trigger('after_update', $this);
  1037. } else {
  1038. // 自动写入
  1039. $this->autoCompleteData($this->insert);
  1040. // 自动写入创建时间和更新时间
  1041. if ($this->autoWriteTimestamp) {
  1042. if ($this->createTime && !isset($this->data[$this->createTime])) {
  1043. $this->data[$this->createTime] = $this->autoWriteTimestamp($this->createTime);
  1044. }
  1045. if ($this->updateTime && !isset($this->data[$this->updateTime])) {
  1046. $this->data[$this->updateTime] = $this->autoWriteTimestamp($this->updateTime);
  1047. }
  1048. }
  1049. if (false === $this->trigger('before_insert', $this)) {
  1050. return false;
  1051. }
  1052. // 检测字段
  1053. $allowFields = $this->checkAllowField(array_merge($this->auto, $this->insert));
  1054. if (!empty($allowFields)) {
  1055. $result = $this->getQuery()->strict(false)->field($allowFields)->insert($this->data, false, false, $sequence);
  1056. } else {
  1057. $result = $this->getQuery()->insert($this->data, false, false, $sequence);
  1058. }
  1059. // 获取自动增长主键
  1060. if ($result && $insertId = $this->getQuery()->getLastInsID($sequence)) {
  1061. foreach ((array) $pk as $key) {
  1062. if (!isset($this->data[$key]) || '' == $this->data[$key]) {
  1063. $this->data[$key] = $insertId;
  1064. }
  1065. }
  1066. }
  1067. // 关联写入
  1068. if (isset($relation)) {
  1069. foreach ($relation as $name => $val) {
  1070. $method = Loader::parseName($name, 1, false);
  1071. $this->$method()->save($val);
  1072. }
  1073. }
  1074. // 标记为更新
  1075. $this->isUpdate = true;
  1076. // 新增回调
  1077. $this->trigger('after_insert', $this);
  1078. }
  1079. // 写入回调
  1080. $this->trigger('after_write', $this);
  1081. // 重新记录原始数据
  1082. $this->origin = $this->data;
  1083. return $result;
  1084. }
  1085. protected function checkAllowField($auto = [])
  1086. {
  1087. if (true === $this->field) {
  1088. $this->field = $this->getQuery()->getTableInfo('', 'fields');
  1089. $field = $this->field;
  1090. } elseif (!empty($this->field)) {
  1091. $field = array_merge($this->field, $auto);
  1092. if ($this->autoWriteTimestamp) {
  1093. array_push($field, $this->createTime, $this->updateTime);
  1094. }
  1095. } elseif (!empty($this->except)) {
  1096. $fields = $this->getQuery()->getTableInfo('', 'fields');
  1097. $field = array_diff($fields, (array) $this->except);
  1098. $this->field = $field;
  1099. } else {
  1100. $field = [];
  1101. }
  1102. if ($this->disuse) {
  1103. // 废弃字段
  1104. $field = array_diff($field, (array) $this->disuse);
  1105. }
  1106. return $field;
  1107. }
  1108. protected function autoRelationUpdate($relation)
  1109. {
  1110. foreach ($relation as $name => $val) {
  1111. if ($val instanceof Model) {
  1112. $val->save();
  1113. } else {
  1114. unset($this->data[$name]);
  1115. $model = $this->getAttr($name);
  1116. if ($model instanceof Model) {
  1117. $model->save($val);
  1118. }
  1119. }
  1120. }
  1121. }
  1122. /**
  1123. * 获取变化的数据 并排除只读数据
  1124. * @access public
  1125. * @return array
  1126. */
  1127. public function getChangedData()
  1128. {
  1129. if ($this->force) {
  1130. $data = $this->data;
  1131. } else {
  1132. $data = array_udiff_assoc($this->data, $this->origin, function ($a, $b) {
  1133. if ((empty($a) || empty($b)) && $a !== $b) {
  1134. return 1;
  1135. }
  1136. return is_object($a) || $a != $b ? 1 : 0;
  1137. });
  1138. }
  1139. if (!empty($this->readonly)) {
  1140. // 只读字段不允许更新
  1141. foreach ($this->readonly as $key => $field) {
  1142. if (isset($data[$field])) {
  1143. unset($data[$field]);
  1144. }
  1145. }
  1146. }
  1147. return $data;
  1148. }
  1149. /**
  1150. * 字段值(延迟)增长
  1151. * @access public
  1152. * @param string $field 字段名
  1153. * @param integer $step 增长值
  1154. * @param integer $lazyTime 延时时间(s)
  1155. * @return integer|true
  1156. * @throws Exception
  1157. */
  1158. public function setInc($field, $step = 1, $lazyTime = 0)
  1159. {
  1160. // 更新条件
  1161. $where = $this->getWhere();
  1162. $result = $this->getQuery()->where($where)->setInc($field, $step, $lazyTime);
  1163. if (true !== $result) {
  1164. $this->data[$field] += $step;
  1165. }
  1166. return $result;
  1167. }
  1168. /**
  1169. * 字段值(延迟)增长
  1170. * @access public
  1171. * @param string $field 字段名
  1172. * @param integer $step 增长值
  1173. * @param integer $lazyTime 延时时间(s)
  1174. * @return integer|true
  1175. * @throws Exception
  1176. */
  1177. public function setDec($field, $step = 1, $lazyTime = 0)
  1178. {
  1179. // 更新条件
  1180. $where = $this->getWhere();
  1181. $result = $this->getQuery()->where($where)->setDec($field, $step, $lazyTime);
  1182. if (true !== $result) {
  1183. $this->data[$field] -= $step;
  1184. }
  1185. return $result;
  1186. }
  1187. /**
  1188. * 获取更新条件
  1189. * @access protected
  1190. * @return mixed
  1191. */
  1192. protected function getWhere()
  1193. {
  1194. // 删除条件
  1195. $pk = $this->getPk();
  1196. if (is_string($pk) && isset($this->data[$pk])) {
  1197. $where = [$pk => $this->data[$pk]];
  1198. } elseif (!empty($this->updateWhere)) {
  1199. $where = $this->updateWhere;
  1200. } else {
  1201. $where = null;
  1202. }
  1203. return $where;
  1204. }
  1205. /**
  1206. * 保存多个数据到当前数据对象
  1207. * @access public
  1208. * @param array $dataSet 数据
  1209. * @param boolean $replace 是否自动识别更新和写入
  1210. * @return array|false
  1211. * @throws \Exception
  1212. */
  1213. public function saveAll($dataSet, $replace = true)
  1214. {
  1215. if ($this->validate) {
  1216. // 数据批量验证
  1217. $validate = $this->validate;
  1218. foreach ($dataSet as $data) {
  1219. if (!$this->validateData($data, $validate)) {
  1220. return false;
  1221. }
  1222. }
  1223. }
  1224. $result = [];
  1225. $db = $this->getQuery();
  1226. $db->startTrans();
  1227. try {
  1228. $pk = $this->getPk();
  1229. if (is_string($pk) && $replace) {
  1230. $auto = true;
  1231. }
  1232. foreach ($dataSet as $key => $data) {
  1233. if ($this->isUpdate || (!empty($auto) && isset($data[$pk]))) {
  1234. $result[$key] = self::update($data, [], $this->field);
  1235. } else {
  1236. $result[$key] = self::create($data, $this->field);
  1237. }
  1238. }
  1239. $db->commit();
  1240. return $this->toCollection($result);
  1241. } catch (\Exception $e) {
  1242. $db->rollback();
  1243. throw $e;
  1244. }
  1245. }
  1246. /**
  1247. * 设置允许写入的字段
  1248. * @access public
  1249. * @param string|array $field 允许写入的字段 如果为true只允许写入数据表字段
  1250. * @return $this
  1251. */
  1252. public function allowField($field)
  1253. {
  1254. if (is_string($field)) {
  1255. $field = explode(',', $field);
  1256. }
  1257. $this->field = $field;
  1258. return $this;
  1259. }
  1260. /**
  1261. * 设置排除写入的字段
  1262. * @access public
  1263. * @param string|array $field 排除允许写入的字段
  1264. * @return $this
  1265. */
  1266. public function except($field)
  1267. {
  1268. if (is_string($field)) {
  1269. $field = explode(',', $field);
  1270. }
  1271. $this->except = $field;
  1272. return $this;
  1273. }
  1274. /**
  1275. * 设置只读字段
  1276. * @access public
  1277. * @param mixed $field 只读字段
  1278. * @return $this
  1279. */
  1280. public function readonly($field)
  1281. {
  1282. if (is_string($field)) {
  1283. $field = explode(',', $field);
  1284. }
  1285. $this->readonly = $field;
  1286. return $this;
  1287. }
  1288. /**
  1289. * 是否为更新数据
  1290. * @access public
  1291. * @param bool $update
  1292. * @param mixed $where
  1293. * @return $this
  1294. */
  1295. public function isUpdate($update = true, $where = null)
  1296. {
  1297. $this->isUpdate = $update;
  1298. if (!empty($where)) {
  1299. $this->updateWhere = $where;
  1300. }
  1301. return $this;
  1302. }
  1303. /**
  1304. * 数据自动完成
  1305. * @access public
  1306. * @param array $auto 要自动更新的字段列表
  1307. * @return void
  1308. */
  1309. protected function autoCompleteData($auto = [])
  1310. {
  1311. foreach ($auto as $field => $value) {
  1312. if (is_integer($field)) {
  1313. $field = $value;
  1314. $value = null;
  1315. }
  1316. if (!isset($this->data[$field])) {
  1317. $default = null;
  1318. } else {
  1319. $default = $this->data[$field];
  1320. }
  1321. $this->setAttr($field, !is_null($value) ? $value : $default);
  1322. }
  1323. }
  1324. /**
  1325. * 删除当前的记录
  1326. * @access public
  1327. * @return integer
  1328. */
  1329. public function delete()
  1330. {
  1331. if (false === $this->trigger('before_delete', $this)) {
  1332. return false;
  1333. }
  1334. // 删除条件
  1335. $where = $this->getWhere();
  1336. // 删除当前模型数据
  1337. $result = $this->getQuery()->where($where)->delete();
  1338. // 关联删除
  1339. if (!empty($this->relationWrite)) {
  1340. foreach ($this->relationWrite as $key => $name) {
  1341. $name = is_numeric($key) ? $name : $key;
  1342. $model = $this->getAttr($name);
  1343. if ($model instanceof Model) {
  1344. $model->delete();
  1345. }
  1346. }
  1347. }
  1348. $this->trigger('after_delete', $this);
  1349. // 清空原始数据
  1350. $this->origin = [];
  1351. return $result;
  1352. }
  1353. /**
  1354. * 设置自动完成的字段( 规则通过修改器定义)
  1355. * @access public
  1356. * @param array $fields 需要自动完成的字段
  1357. * @return $this
  1358. */
  1359. public function auto($fields)
  1360. {
  1361. $this->auto = $fields;
  1362. return $this;
  1363. }
  1364. /**
  1365. * 设置字段验证
  1366. * @access public
  1367. * @param array|string|bool $rule 验证规则 true表示自动读取验证器类
  1368. * @param array $msg 提示信息
  1369. * @param bool $batch 批量验证
  1370. * @return $this
  1371. */
  1372. public function validate($rule = true, $msg = [], $batch = false)
  1373. {
  1374. if (is_array($rule)) {
  1375. $this->validate = [
  1376. 'rule' => $rule,
  1377. 'msg' => $msg,
  1378. ];
  1379. } else {
  1380. $this->validate = true === $rule ? $this->name : $rule;
  1381. }
  1382. $this->batchValidate = $batch;
  1383. return $this;
  1384. }
  1385. /**
  1386. * 设置验证失败后是否抛出异常
  1387. * @access public
  1388. * @param bool $fail 是否抛出异常
  1389. * @return $this
  1390. */
  1391. public function validateFailException($fail = true)
  1392. {
  1393. $this->failException = $fail;
  1394. return $this;
  1395. }
  1396. /**
  1397. * 自动验证数据
  1398. * @access protected
  1399. * @param array $data 验证数据
  1400. * @param mixed $rule 验证规则
  1401. * @param bool $batch 批量验证
  1402. * @return bool
  1403. */
  1404. protected function validateData($data, $rule = null, $batch = null)
  1405. {
  1406. $info = is_null($rule) ? $this->validate : $rule;
  1407. if (!empty($info)) {
  1408. if (is_array($info)) {
  1409. $validate = Loader::validate();
  1410. $validate->rule($info['rule']);
  1411. $validate->message($info['msg']);
  1412. } else {
  1413. $name = is_string($info) ? $info : $this->name;
  1414. if (strpos($name, '.')) {
  1415. list($name, $scene) = explode('.', $name);
  1416. }
  1417. $validate = Loader::validate($name);
  1418. if (!empty($scene)) {
  1419. $validate->scene($scene);
  1420. }
  1421. }
  1422. $batch = is_null($batch) ? $this->batchValidate : $batch;
  1423. if (!$validate->batch($batch)->check($data)) {
  1424. $this->error = $validate->getError();
  1425. if ($this->failException) {
  1426. throw new ValidateException($this->error);
  1427. } else {
  1428. return false;
  1429. }
  1430. }
  1431. $this->validate = null;
  1432. }
  1433. return true;
  1434. }
  1435. /**
  1436. * 返回模型的错误信息
  1437. * @access public
  1438. * @return string|array
  1439. */
  1440. public function getError()
  1441. {
  1442. return $this->error;
  1443. }
  1444. /**
  1445. * 注册回调方法
  1446. * @access public
  1447. * @param string $event 事件名
  1448. * @param callable $callback 回调方法
  1449. * @param bool $override 是否覆盖
  1450. * @return void
  1451. */
  1452. public static function event($event, $callback, $override = false)
  1453. {
  1454. $class = get_called_class();
  1455. if ($override) {
  1456. self::$event[$class][$event] = [];
  1457. }
  1458. self::$event[$class][$event][] = $callback;
  1459. }
  1460. /**
  1461. * 触发事件
  1462. * @access protected
  1463. * @param string $event 事件名
  1464. * @param mixed $params 传入参数(引用)
  1465. * @return bool
  1466. */
  1467. protected function trigger($event, &$params)
  1468. {
  1469. if (isset(self::$event[$this->class][$event])) {
  1470. foreach (self::$event[$this->class][$event] as $callback) {
  1471. if (is_callable($callback)) {
  1472. $result = call_user_func_array($callback, [ & $params]);
  1473. if (false === $result) {
  1474. return false;
  1475. }
  1476. }
  1477. }
  1478. }
  1479. return true;
  1480. }
  1481. /**
  1482. * 写入数据
  1483. * @access public
  1484. * @param array $data 数据数组
  1485. * @param array|true $field 允许字段
  1486. * @return $this
  1487. */
  1488. public static function create($data = [], $field = null)
  1489. {
  1490. $model = new static();
  1491. if (!empty($field)) {
  1492. $model->allowField($field);
  1493. }
  1494. $model->isUpdate(false)->save($data, []);
  1495. return $model;
  1496. }
  1497. /**
  1498. * 更新数据
  1499. * @access public
  1500. * @param array $data 数据数组
  1501. * @param array $where 更新条件
  1502. * @param array|true $field 允许字段
  1503. * @return $this
  1504. */
  1505. public static function update($data = [], $where = [], $field = null)
  1506. {
  1507. $model = new static();
  1508. if (!empty($field)) {
  1509. $model->allowField($field);
  1510. }
  1511. $result = $model->isUpdate(true)->save($data, $where);
  1512. return $model;
  1513. }
  1514. /**
  1515. * 查找单条记录
  1516. * @access public
  1517. * @param mixed $data 主键值或者查询条件(闭包)
  1518. * @param array|string $with 关联预查询
  1519. * @param bool $cache 是否缓存
  1520. * @return static|null
  1521. * @throws exception\DbException
  1522. */
  1523. public static function get($data, $with = [], $cache = false)
  1524. {
  1525. if (is_null($data)) {
  1526. return;
  1527. }
  1528. if (true === $with || is_int($with)) {
  1529. $cache = $with;
  1530. $with = [];
  1531. }
  1532. $query = static::parseQuery($data, $with, $cache);
  1533. return $query->find($data);
  1534. }
  1535. /**
  1536. * 查找所有记录
  1537. * @access public
  1538. * @param mixed $data 主键列表或者查询条件(闭包)
  1539. * @param array|string $with 关联预查询
  1540. * @param bool $cache 是否缓存
  1541. * @return static[]|false
  1542. * @throws exception\DbException
  1543. */
  1544. public static function all($data = null, $with = [], $cache = false)
  1545. {
  1546. if (true === $with || is_int($with)) {
  1547. $cache = $with;
  1548. $with = [];
  1549. }
  1550. $query = static::parseQuery($data, $with, $cache);
  1551. return $query->select($data);
  1552. }
  1553. /**
  1554. * 分析查询表达式
  1555. * @access public
  1556. * @param mixed $data 主键列表或者查询条件(闭包)
  1557. * @param string $with 关联预查询
  1558. * @param bool $cache 是否缓存
  1559. * @return Query
  1560. */
  1561. protected static function parseQuery(&$data, $with, $cache)
  1562. {
  1563. $result = self::with($with)->cache($cache);
  1564. if (is_array($data) && key($data) !== 0) {
  1565. $result = $result->where($data);
  1566. $data = null;
  1567. } elseif ($data instanceof \Closure) {
  1568. call_user_func_array($data, [ & $result]);
  1569. $data = null;
  1570. } elseif ($data instanceof Query) {
  1571. $result = $data->with($with)->cache($cache);
  1572. $data = null;
  1573. }
  1574. return $result;
  1575. }
  1576. /**
  1577. * 删除记录
  1578. * @access public
  1579. * @param mixed $data 主键列表 支持闭包查询条件
  1580. * @return integer 成功删除的记录数
  1581. */
  1582. public static function destroy($data)
  1583. {
  1584. $model = new static();
  1585. $query = $model->db();
  1586. if (empty($data) && 0 !== $data) {
  1587. return 0;
  1588. } elseif (is_array($data) && key($data) !== 0) {
  1589. $query->where($data);
  1590. $data = null;
  1591. } elseif ($data instanceof \Closure) {
  1592. call_user_func_array($data, [ & $query]);
  1593. $data = null;
  1594. }
  1595. $resultSet = $query->select($data);
  1596. $count = 0;
  1597. if ($resultSet) {
  1598. foreach ($resultSet as $data) {
  1599. $result = $data->delete();
  1600. $count += $result;
  1601. }
  1602. }
  1603. return $count;
  1604. }
  1605. /**
  1606. * 命名范围
  1607. * @access public
  1608. * @param string|array|\Closure $name 命名范围名称 逗号分隔
  1609. * @internal mixed ...$params 参数调用
  1610. * @return Query
  1611. */
  1612. public static function scope($name)
  1613. {
  1614. $model = new static();
  1615. $query = $model->db();
  1616. $params = func_get_args();
  1617. array_shift($params);
  1618. array_unshift($params, $query);
  1619. if ($name instanceof \Closure) {
  1620. call_user_func_array($name, $params);
  1621. } elseif (is_string($name)) {
  1622. $name = explode(',', $name);
  1623. }
  1624. if (is_array($name)) {
  1625. foreach ($name as $scope) {
  1626. $method = 'scope' . trim($scope);
  1627. if (method_exists($model, $method)) {
  1628. call_user_func_array([$model, $method], $params);
  1629. }
  1630. }
  1631. }
  1632. return $query;
  1633. }
  1634. /**
  1635. * 设置是否使用全局查询范围
  1636. * @param bool $use 是否启用全局查询范围
  1637. * @access public
  1638. * @return Query
  1639. */
  1640. public static function useGlobalScope($use)
  1641. {
  1642. $model = new static();
  1643. return $model->db($use);
  1644. }
  1645. /**
  1646. * 根据关联条件查询当前模型
  1647. * @access public
  1648. * @param string $relation 关联方法名
  1649. * @param mixed $operator 比较操作符
  1650. * @param integer $count 个数
  1651. * @param string $id 关联表的统计字段
  1652. * @return Relation|Query
  1653. */
  1654. public static function has($relation, $operator = '>=', $count = 1, $id = '*')
  1655. {
  1656. $relation = (new static())->$relation();
  1657. if (is_array($operator) || $operator instanceof \Closure) {
  1658. return $relation->hasWhere($operator);
  1659. }
  1660. return $relation->has($operator, $count, $id);
  1661. }
  1662. /**
  1663. * 根据关联条件查询当前模型
  1664. * @access public
  1665. * @param string $relation 关联方法名
  1666. * @param mixed $where 查询条件(数组或者闭包)
  1667. * @param mixed $fields 字段
  1668. * @return Relation|Query
  1669. */
  1670. public static function hasWhere($relation, $where = [], $fields = null)
  1671. {
  1672. return (new static())->$relation()->hasWhere($where, $fields);
  1673. }
  1674. /**
  1675. * 解析模型的完整命名空间
  1676. * @access public
  1677. * @param string $model 模型名(或者完整类名)
  1678. * @return string
  1679. */
  1680. protected function parseModel($model)
  1681. {
  1682. if (false === strpos($model, '\\')) {
  1683. $path = explode('\\', get_called_class());
  1684. array_pop($path);
  1685. array_push($path, Loader::parseName($model, 1));
  1686. $model = implode('\\', $path);
  1687. }
  1688. return $model;
  1689. }
  1690. /**
  1691. * 查询当前模型的关联数据
  1692. * @access public
  1693. * @param string|array $relations 关联名
  1694. * @return $this
  1695. */
  1696. public function relationQuery($relations)
  1697. {
  1698. if (is_string($relations)) {
  1699. $relations = explode(',', $relations);
  1700. }
  1701. foreach ($relations as $key => $relation) {
  1702. $subRelation = '';
  1703. $closure = null;
  1704. if ($relation instanceof \Closure) {
  1705. // 支持闭包查询过滤关联条件
  1706. $closure = $relation;
  1707. $relation = $key;
  1708. }
  1709. if (is_array($relation)) {
  1710. $subRelation = $relation;
  1711. $relation = $key;
  1712. } elseif (strpos($relation, '.')) {
  1713. list($relation, $subRelation) = explode('.', $relation, 2);
  1714. }
  1715. $method = Loader::parseName($relation, 1, false);
  1716. $this->data[$relation] = $this->$method()->getRelation($subRelation, $closure);
  1717. }
  1718. return $this;
  1719. }
  1720. /**
  1721. * 预载入关联查询 返回数据集
  1722. * @access public
  1723. * @param array $resultSet 数据集
  1724. * @param string $relation 关联名
  1725. * @return array
  1726. */
  1727. public function eagerlyResultSet(&$resultSet, $relation)
  1728. {
  1729. $relations = is_string($relation) ? explode(',', $relation) : $relation;
  1730. foreach ($relations as $key => $relation) {
  1731. $subRelation = '';
  1732. $closure = false;
  1733. if ($relation instanceof \Closure) {
  1734. $closure = $relation;
  1735. $relation = $key;
  1736. }
  1737. if (is_array($relation)) {
  1738. $subRelation = $relation;
  1739. $relation = $key;
  1740. } elseif (strpos($relation, '.')) {
  1741. list($relation, $subRelation) = explode('.', $relation, 2);
  1742. }
  1743. $relation = Loader::parseName($relation, 1, false);
  1744. $this->$relation()->eagerlyResultSet($resultSet, $relation, $subRelation, $closure);
  1745. }
  1746. }
  1747. /**
  1748. * 预载入关联查询 返回模型对象
  1749. * @access public
  1750. * @param Model $result 数据对象
  1751. * @param string $relation 关联名
  1752. * @return Model
  1753. */
  1754. public function eagerlyResult(&$result, $relation)
  1755. {
  1756. $relations = is_string($relation) ? explode(',', $relation) : $relation;
  1757. foreach ($relations as $key => $relation) {
  1758. $subRelation = '';
  1759. $closure = false;
  1760. if ($relation instanceof \Closure) {
  1761. $closure = $relation;
  1762. $relation = $key;
  1763. }
  1764. if (is_array($relation)) {
  1765. $subRelation = $relation;
  1766. $relation = $key;
  1767. } elseif (strpos($relation, '.')) {
  1768. list($relation, $subRelation) = explode('.', $relation, 2);
  1769. }
  1770. $relation = Loader::parseName($relation, 1, false);
  1771. $this->$relation()->eagerlyResult($result, $relation, $subRelation, $closure);
  1772. }
  1773. }
  1774. /**
  1775. * 关联统计
  1776. * @access public
  1777. * @param Model $result 数据对象
  1778. * @param string|array $relation 关联名
  1779. * @return void
  1780. */
  1781. public function relationCount(&$result, $relation)
  1782. {
  1783. $relations = is_string($relation) ? explode(',', $relation) : $relation;
  1784. foreach ($relations as $key => $relation) {
  1785. $closure = false;
  1786. if ($relation instanceof \Closure) {
  1787. $closure = $relation;
  1788. $relation = $key;
  1789. } elseif (is_string($key)) {
  1790. $name = $relation;
  1791. $relation = $key;
  1792. }
  1793. $relation = Loader::parseName($relation, 1, false);
  1794. $count = $this->$relation()->relationCount($result, $closure);
  1795. if (!isset($name)) {
  1796. $name = Loader::parseName($relation) . '_count';
  1797. }
  1798. $result->setAttr($name, $count);
  1799. }
  1800. }
  1801. /**
  1802. * 获取模型的默认外键名
  1803. * @access public
  1804. * @param string $name 模型名
  1805. * @return string
  1806. */
  1807. protected function getForeignKey($name)
  1808. {
  1809. if (strpos($name, '\\')) {
  1810. $name = basename(str_replace('\\', '/', $name));
  1811. }
  1812. return Loader::parseName($name) . '_id';
  1813. }
  1814. /**
  1815. * HAS ONE 关联定义
  1816. * @access public
  1817. * @param string $model 模型名
  1818. * @param string $foreignKey 关联外键
  1819. * @param string $localKey 当前模型主键
  1820. * @param array $alias 别名定义(已经废弃)
  1821. * @param string $joinType JOIN类型
  1822. * @return HasOne
  1823. */
  1824. public function hasOne($model, $foreignKey = '', $localKey = '', $alias = [], $joinType = 'INNER')
  1825. {
  1826. // 记录当前关联信息
  1827. $model = $this->parseModel($model);
  1828. $localKey = $localKey ?: $this->getPk();
  1829. $foreignKey = $foreignKey ?: $this->getForeignKey($this->name);
  1830. return new HasOne($this, $model, $foreignKey, $localKey, $joinType);
  1831. }
  1832. /**
  1833. * BELONGS TO 关联定义
  1834. * @access public
  1835. * @param string $model 模型名
  1836. * @param string $foreignKey 关联外键
  1837. * @param string $localKey 关联主键
  1838. * @param array $alias 别名定义(已经废弃)
  1839. * @param string $joinType JOIN类型
  1840. * @return BelongsTo
  1841. */
  1842. public function belongsTo($model, $foreignKey = '', $localKey = '', $alias = [], $joinType = 'INNER')
  1843. {
  1844. // 记录当前关联信息
  1845. $model = $this->parseModel($model);
  1846. $foreignKey = $foreignKey ?: $this->getForeignKey($model);
  1847. $localKey = $localKey ?: (new $model)->getPk();
  1848. $trace = debug_backtrace(false, 2);
  1849. $relation = Loader::parseName($trace[1]['function']);
  1850. return new BelongsTo($this, $model, $foreignKey, $localKey, $joinType, $relation);
  1851. }
  1852. /**
  1853. * HAS MANY 关联定义
  1854. * @access public
  1855. * @param string $model 模型名
  1856. * @param string $foreignKey 关联外键
  1857. * @param string $localKey 当前模型主键
  1858. * @return HasMany
  1859. */
  1860. public function hasMany($model, $foreignKey = '', $localKey = '')
  1861. {
  1862. // 记录当前关联信息
  1863. $model = $this->parseModel($model);
  1864. $localKey = $localKey ?: $this->getPk();
  1865. $foreignKey = $foreignKey ?: $this->getForeignKey($this->name);
  1866. return new HasMany($this, $model, $foreignKey, $localKey);
  1867. }
  1868. /**
  1869. * HAS MANY 远程关联定义
  1870. * @access public
  1871. * @param string $model 模型名
  1872. * @param string $through 中间模型名
  1873. * @param string $foreignKey 关联外键
  1874. * @param string $throughKey 关联外键
  1875. * @param string $localKey 当前模型主键
  1876. * @return HasManyThrough
  1877. */
  1878. public function hasManyThrough($model, $through, $foreignKey = '', $throughKey = '', $localKey = '')
  1879. {
  1880. // 记录当前关联信息
  1881. $model = $this->parseModel($model);
  1882. $through = $this->parseModel($through);
  1883. $localKey = $localKey ?: $this->getPk();
  1884. $foreignKey = $foreignKey ?: $this->getForeignKey($this->name);
  1885. $throughKey = $throughKey ?: $this->getForeignKey($through);
  1886. return new HasManyThrough($this, $model, $through, $foreignKey, $throughKey, $localKey);
  1887. }
  1888. /**
  1889. * BELONGS TO MANY 关联定义
  1890. * @access public
  1891. * @param string $model 模型名
  1892. * @param string $table 中间表名
  1893. * @param string $foreignKey 关联外键
  1894. * @param string $localKey 当前模型关联键
  1895. * @return BelongsToMany
  1896. */
  1897. public function belongsToMany($model, $table = '', $foreignKey = '', $localKey = '')
  1898. {
  1899. // 记录当前关联信息
  1900. $model = $this->parseModel($model);
  1901. $name = Loader::parseName(basename(str_replace('\\', '/', $model)));
  1902. $table = $table ?: Loader::parseName($this->name) . '_' . $name;
  1903. $foreignKey = $foreignKey ?: $name . '_id';
  1904. $localKey = $localKey ?: $this->getForeignKey($this->name);
  1905. return new BelongsToMany($this, $model, $table, $foreignKey, $localKey);
  1906. }
  1907. /**
  1908. * MORPH MANY 关联定义
  1909. * @access public
  1910. * @param string $model 模型名
  1911. * @param string|array $morph 多态字段信息
  1912. * @param string $type 多态类型
  1913. * @return MorphMany
  1914. */
  1915. public function morphMany($model, $morph = null, $type = '')
  1916. {
  1917. // 记录当前关联信息
  1918. $model = $this->parseModel($model);
  1919. if (is_null($morph)) {
  1920. $trace = debug_backtrace(false, 2);
  1921. $morph = Loader::parseName($trace[1]['function']);
  1922. }
  1923. $type = $type ?: get_class($this);
  1924. if (is_array($morph)) {
  1925. list($morphType, $foreignKey) = $morph;
  1926. } else {
  1927. $morphType = $morph . '_type';
  1928. $foreignKey = $morph . '_id';
  1929. }
  1930. return new MorphMany($this, $model, $foreignKey, $morphType, $type);
  1931. }
  1932. /**
  1933. * MORPH One 关联定义
  1934. * @access public
  1935. * @param string $model 模型名
  1936. * @param string|array $morph 多态字段信息
  1937. * @param string $type 多态类型
  1938. * @return MorphOne
  1939. */
  1940. public function morphOne($model, $morph = null, $type = '')
  1941. {
  1942. // 记录当前关联信息
  1943. $model = $this->parseModel($model);
  1944. if (is_null($morph)) {
  1945. $trace = debug_backtrace(false, 2);
  1946. $morph = Loader::parseName($trace[1]['function']);
  1947. }
  1948. $type = $type ?: get_class($this);
  1949. if (is_array($morph)) {
  1950. list($morphType, $foreignKey) = $morph;
  1951. } else {
  1952. $morphType = $morph . '_type';
  1953. $foreignKey = $morph . '_id';
  1954. }
  1955. return new MorphOne($this, $model, $foreignKey, $morphType, $type);
  1956. }
  1957. /**
  1958. * MORPH TO 关联定义
  1959. * @access public
  1960. * @param string|array $morph 多态字段信息
  1961. * @param array $alias 多态别名定义
  1962. * @return MorphTo
  1963. */
  1964. public function morphTo($morph = null, $alias = [])
  1965. {
  1966. $trace = debug_backtrace(false, 2);
  1967. $relation = Loader::parseName($trace[1]['function']);
  1968. if (is_null($morph)) {
  1969. $morph = $relation;
  1970. }
  1971. // 记录当前关联信息
  1972. if (is_array($morph)) {
  1973. list($morphType, $foreignKey) = $morph;
  1974. } else {
  1975. $morphType = $morph . '_type';
  1976. $foreignKey = $morph . '_id';
  1977. }
  1978. return new MorphTo($this, $morphType, $foreignKey, $alias, $relation);
  1979. }
  1980. public function __call($method, $args)
  1981. {
  1982. $query = $this->db(true, false);
  1983. if (method_exists($this, 'scope' . $method)) {
  1984. // 动态调用命名范围
  1985. $method = 'scope' . $method;
  1986. array_unshift($args, $query);
  1987. call_user_func_array([$this, $method], $args);
  1988. return $this;
  1989. } else {
  1990. return call_user_func_array([$query, $method], $args);
  1991. }
  1992. }
  1993. public static function __callStatic($method, $args)
  1994. {
  1995. $model = new static();
  1996. $query = $model->db();
  1997. if (method_exists($model, 'scope' . $method)) {
  1998. // 动态调用命名范围
  1999. $method = 'scope' . $method;
  2000. array_unshift($args, $query);
  2001. call_user_func_array([$model, $method], $args);
  2002. return $query;
  2003. } else {
  2004. return call_user_func_array([$query, $method], $args);
  2005. }
  2006. }
  2007. /**
  2008. * 修改器 设置数据对象的值
  2009. * @access public
  2010. * @param string $name 名称
  2011. * @param mixed $value 值
  2012. * @return void
  2013. */
  2014. public function __set($name, $value)
  2015. {
  2016. $this->setAttr($name, $value);
  2017. }
  2018. /**
  2019. * 获取器 获取数据对象的值
  2020. * @access public
  2021. * @param string $name 名称
  2022. * @return mixed
  2023. */
  2024. public function __get($name)
  2025. {
  2026. return $this->getAttr($name);
  2027. }
  2028. /**
  2029. * 检测数据对象的值
  2030. * @access public
  2031. * @param string $name 名称
  2032. * @return boolean
  2033. */
  2034. public function __isset($name)
  2035. {
  2036. try {
  2037. if (array_key_exists($name, $this->data) || array_key_exists($name, $this->relation)) {
  2038. return true;
  2039. } else {
  2040. $this->getAttr($name);
  2041. return true;
  2042. }
  2043. } catch (InvalidArgumentException $e) {
  2044. return false;
  2045. }
  2046. }
  2047. /**
  2048. * 销毁数据对象的值
  2049. * @access public
  2050. * @param string $name 名称
  2051. * @return void
  2052. */
  2053. public function __unset($name)
  2054. {
  2055. unset($this->data[$name], $this->relation[$name]);
  2056. }
  2057. public function __toString()
  2058. {
  2059. return $this->toJson();
  2060. }
  2061. // JsonSerializable
  2062. public function jsonSerialize()
  2063. {
  2064. return $this->toArray();
  2065. }
  2066. // ArrayAccess
  2067. public function offsetSet($name, $value)
  2068. {
  2069. $this->setAttr($name, $value);
  2070. }
  2071. public function offsetExists($name)
  2072. {
  2073. return $this->__isset($name);
  2074. }
  2075. public function offsetUnset($name)
  2076. {
  2077. $this->__unset($name);
  2078. }
  2079. public function offsetGet($name)
  2080. {
  2081. return $this->getAttr($name);
  2082. }
  2083. /**
  2084. * 解序列化后处理
  2085. */
  2086. public function __wakeup()
  2087. {
  2088. $this->initialize();
  2089. }
  2090. /**
  2091. * 模型事件快捷方法
  2092. * @param $callback
  2093. * @param bool $override
  2094. */
  2095. protected static function beforeInsert($callback, $override = false)
  2096. {
  2097. self::event('before_insert', $callback, $override);
  2098. }
  2099. protected static function afterInsert($callback, $override = false)
  2100. {
  2101. self::event('after_insert', $callback, $override);
  2102. }
  2103. protected static function beforeUpdate($callback, $override = false)
  2104. {
  2105. self::event('before_update', $callback, $override);
  2106. }
  2107. protected static function afterUpdate($callback, $override = false)
  2108. {
  2109. self::event('after_update', $callback, $override);
  2110. }
  2111. protected static function beforeWrite($callback, $override = false)
  2112. {
  2113. self::event('before_write', $callback, $override);
  2114. }
  2115. protected static function afterWrite($callback, $override = false)
  2116. {
  2117. self::event('after_write', $callback, $override);
  2118. }
  2119. protected static function beforeDelete($callback, $override = false)
  2120. {
  2121. self::event('before_delete', $callback, $override);
  2122. }
  2123. protected static function afterDelete($callback, $override = false)
  2124. {
  2125. self::event('after_delete', $callback, $override);
  2126. }
  2127. }