Model.php 70 KB

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