Model.php 69 KB

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