Model.php 70 KB

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