Model.php 65 KB

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