Model.php 70 KB

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