Model.php 70 KB

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