Model.php 56 KB

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