Model.php 70 KB

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