Model.php 69 KB

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