Model.php 67 KB

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