Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

2351 linhas
69 KiB

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