Model.php 70 KB

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