Model.php 70 KB

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