暫無描述
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Model.php 69KB

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