-
Notifications
You must be signed in to change notification settings - Fork 4
/
Model.php
2907 lines (2661 loc) · 89.5 KB
/
Model.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think;
use think\exception\ErrorCode;
/**
* ThinkPHP Model模型类
* 实现了ORM和ActiveRecords模式
*
* @method $this alias(string $alias)
* @method $this strict(bool $strict)
* @method $this order(mixed $order)
* @method $this having(string $having)
* @method $this group(string $group)
* @method $this lock(bool $lock)
* @method $this distinct(bool $distinct)
* @method $this auto(array $auto)
* @method $this count()
* @method $this sum(string $field)
* @method $this avg(string $field)
* @method $this min(string $field)
* @method $this max(string $field)
*/
class Model
{
// 操作状态
const MODEL_INSERT = 1; // 插入模型数据
const MODEL_UPDATE = 2; // 更新模型数据
const MODEL_BOTH = 3; // 包含上面两种方式
const MUST_VALIDATE = 1; // 必须验证
const EXISTS_VALIDATE = 0; // 表单存在字段则验证
const VALUE_VALIDATE = 2; // 表单值不为空则验证
/**
* 当前数据库操作对象
* @var \think\Db
*/
protected $db = null;
// 数据库对象池
private $_db = [];
// 主键名称
protected $pk = 'id';
// 主键是否自动增长
protected $autoinc = false;
// 数据表前缀
protected $tablePrefix = null;
// 模型名称
protected $name = '';
// 数据库名称
protected $dbName = '';
//数据库配置
protected $connection = '';
//数据更新新数据
protected $newUpdateData = [];
//数据更新旧数据
protected $oldUpdateData = [];
//数据更新主键记录
protected $oldUpdateKey = null;
//数据删除旧数据
protected $oldDeleteData = [];
//数据删除主键记录
protected $oldDeleteKey = '';
// 数据表名(不包含表前缀)
protected $tableName = '';
// 实际数据表名(包含表前缀)
protected $trueTableName = '';
// 最近错误信息
protected $error = '';
// 最近错误码
protected $errorCode = '';
// 检查唯一性存在值
protected $checkUniqueExitData = [];
// 成功消息
protected $successMsg = '';
// 字段信息
protected $fields = [];
// 数据信息
protected $data = [];
// 查询表达式参数
protected $options = [];
protected $_validate = []; // 自动验证定义
protected $_validate_after_auto = []; // 自动完成后验证
protected $_auto = []; // 自动完成定义
protected $_map = []; // 字段映射定义
protected $_scope = []; // 命名范围定义
// 显示属性
protected $visible = [];
// 隐藏属性
protected $hidden = [];
// 追加属性
protected $append = [];
// 追加自定义字段属性
protected $appendCustomField = [];
// 是否自动检测数据表字段信息
protected $autoCheckFields = true;
// 是否批处理验证
protected $patchValidate = false;
// 链操作方法列表
protected $methods = ['strict', 'order', 'alias', 'having', 'group', 'lock', 'distinct', 'auto', 'filter', 'validate', 'result', 'token', 'index', 'force', 'master'];
// 支持的验证规则
protected $typeMsg = [
'unique' => 'Validate_Unique',
'confirm' => 'Validate_Confirm',
'in' => 'Validate_In',
'notin' => 'Validate_NotIn',
'between' => 'Validate_Between',
'notbetween' => 'Validate_NotBetween',
'equal' => 'Validate_Eq',
'notequal' => 'Validate_NotEq',
'length' => 'Validate_Length',
'expire' => 'Validate_Expire',
'ip_allow' => 'Validate_AllowIp',
'ip_deny' => 'Validate_DenyIp',
'array' => 'Validate_Array',
'number' => 'Validate_Number',
'integer' => 'Validate_Integer',
'require' => 'Validate_Require',
'accepted' => 'Validate_Accepted',
'date' => 'Validate_Date',
'phone' => 'Validate_Phone',
'password_strength' => 'Validate_Password_Strength',
'activeUrl' => 'Validate_ActiveUrl',
'alpha' => 'Validate_Alpha',
'alphaNum' => 'Validate_AlphaNum',
'alphaDash' => 'Validate_AlphaDash',
'chs' => 'Validate_Chs',
'chsAlpha' => 'Validate_ChsAlpha',
'chsAlphaNum' => 'Validate_ChsAlphaNum',
'chsDash' => 'Validate_ChsDash',
'AuthMethod' => 'Validate_AuthMethod',
'ip' => 'Validate_Ip',
'url' => 'Validate_Url',
'float' => 'Validate_Float',
'email' => 'Validate_Email',
'boolean' => 'Validate_Boolean',
'regex' => 'Validate_Regex'
];
// 定义返回数据
public $_resData = [];
// 字段配置字典数据
public $fieldConfigDictionary = [];
// 查询模块模型关联
protected $queryModuleRelation = [];
// 查询需要join查询的模块
protected $queryModuleLfetJoinRelation = [];
// 查询通过自定义字段水平关联的模块
protected $queryModuleHorizontalRelation = [];
// 查询实体关联的模块
protected $queryModuleEntityRelation = [];
// 查询一对多的模块
protected $queryModuleHasManyRelation = [];
// 查询实体关联的模块查询字段列表
protected $queryModuleRelationFields = [];
// 临时存储当前模块字段映射数据
protected $queryModuleFieldDict = [];
// 查询主键IDs
protected $queryModulePrimaryKeyIds = [];
// 复杂查询字段映射
protected $queryComplexModuleMapping = [];
// 复杂查询自定义字段映射
protected $queryComplexCustomFieldMapping = [];
// 复杂查询水平关联自定义字段映射
protected $queryComplexHorizontalCustomFieldMapping = [];
// 复杂查询关联模型自定义字段映射
protected $queryComplexRelationCustomFields = [];
// 复杂过滤条件涉及到的关联模块
protected $complexFilterRelatedModule = [];
// 是否是复杂过滤条件
protected $isComplexFilter = false;
// 当前模块code
protected $currentModuleCode = '';
// 查询model对象
protected $moduleModel = null;
/**
* 架构函数
* 取得DB类的实例对象 字段检查
* @access public
* @param string $name 模型名称
* @param string $tablePrefix 表前缀
* @param mixed $connection 数据库连接信息
* @throws \Exception
*/
public function __construct($name = '', $tablePrefix = '', $connection = '')
{
// 模型初始化
$this->_initialize();
// 获取模型名称
if (!empty($name)) {
if (strpos($name, '.')) {
// 支持 数据库名.模型名的 定义
list($this->dbName, $this->name) = explode('.', $name);
} else {
$this->name = $name;
}
} elseif (empty($this->name)) {
$this->name = $this->getModelName();
}
// 设置表前缀
if (is_null($tablePrefix)) {
// 前缀为Null表示没有前缀
$this->tablePrefix = '';
} elseif ('' != $tablePrefix) {
$this->tablePrefix = $tablePrefix;
} elseif (!isset($this->tablePrefix)) {
$this->tablePrefix = C('DB_PREFIX');
}
// 数据库初始化操作
// 获取数据库操作对象
// 当前模型有独立的数据库连接信息
$this->db(0, empty($this->connection) ? $connection : $this->connection, true);
}
/**
* 格式化字段查询条件值类型
* @param $tableName
* @param $fieldName
* @param $value
* @return int
*/
protected function formatFieldQueryValue($tableName, $fieldName, $value)
{
// 转换驼峰名称
$moduleCode = un_camelize($tableName);
// 判断值
if ($this->fieldConfigDictionary[$moduleCode][$fieldName]["type"] === "int") {
return intval($value);
} else {
return $value;
}
}
/**
* 自动检测数据表信息
* @access protected
* @return void
*/
protected function _checkTableInfo()
{
// 如果不是Model类 自动记录数据表信息
// 只在第一次执行记录
if (empty($this->fields)) {
// 每次都会读取数据表信息
$fields = $this->flush();
if (!empty($fields)) {
$this->fields = $fields;
if (!empty($fields['_pk'])) {
$this->pk = $fields['_pk'];
}
return;
}
}
}
/**
* 获取字段信息并缓存
* @param string $tableName
* @param bool $must 是否必须刷新
* @return mixed
*/
public function flush($tableName = '', $must = false)
{
if (empty($tableName)) {
$tableName = $this->getTableName();
}
if ($must === false && C('DB_FIELDS_CACHE')) {
$fieldsCache = S('fields_' . strtolower($tableName));
if (!empty($fieldsCache)) {
return $fieldsCache;
}
}
// 缓存不存在则查询数据表信息
$this->db->setModel($this->name);
$fields = $this->db->getFields($tableName);
if (!empty($fields)) {
$this->fields = array_keys($fields);
unset($this->fields['_pk']);
foreach ($fields as $key => $val) {
// 记录字段类型
$type[$key] = $val['type'];
if ($val['primary']) {
// 增加复合主键支持
if (isset($this->fields['_pk']) && null != $this->fields['_pk']) {
if (is_string($this->fields['_pk'])) {
$this->pk = [$this->fields['_pk']];
$this->fields['_pk'] = $this->pk;
}
$this->pk[] = $key;
$this->fields['_pk'][] = $key;
} else {
$this->pk = $key;
$this->fields['_pk'] = $key;
}
if ($val['autoinc']) {
$this->autoinc = true;
}
}
}
// 记录字段类型信息
$this->fields['_type'] = $type;
// 增加缓存开关控制
if (C('DB_FIELDS_CACHE')) {
// 永久缓存数据表信息, 缓存一个小时
S('fields_' . strtolower($tableName), $this->fields, 3600);
}
}
}
/**
* 设置数据对象的值
* @access public
* @param string $name 名称
* @param mixed $value 值
* @return void
*/
public function __set($name, $value)
{
// 设置数据对象属性
$this->data[$name] = $value;
}
/**
* 获取数据对象的值
* @access public
* @param string $name 名称
* @return mixed
*/
public function __get($name)
{
return $this->data[$name] ?? null;
}
/**
* 检测数据对象的值
* @access public
* @param string $name 名称
* @return boolean
*/
public function __isset($name)
{
return isset($this->data[$name]);
}
/**
* 销毁数据对象的值
* @access public
* @param string $name 名称
* @return void
*/
public function __unset($name)
{
unset($this->data[$name]);
}
/**
* 利用__call方法实现一些特殊的Model方法
* @access public
* @param string $method 方法名称
* @param array $args 调用参数
* @return $this|mixed|Model
* @throws \Exception
*/
public function __call($method, $args)
{
if (in_array(strtolower($method), $this->methods, true)) {
// 连贯操作的实现
$this->options[strtolower($method)] = $args[0];
return $this;
} elseif (in_array(strtolower($method), ['count', 'sum', 'min', 'max', 'avg'], true)) {
// 统计查询的实现
$field = $args[0] ?? '*';
return $this->getField(strtoupper($method) . '(' . $field . ') AS tp_' . $method);
} elseif (strtolower(substr($method, 0, 5)) == 'getby') {
// 根据某个字段获取记录
$field = parse_name(substr($method, 5));
$where[$field] = $args[0];
return $this->where($where)->find();
} elseif (strtolower(substr($method, 0, 10)) == 'getfieldby') {
// 根据某个字段获取记录的某个值
$name = parse_name(substr($method, 10));
$where[$name] = $args[0];
return $this->where($where)->getField($args[1]);
} elseif (isset($this->_scope[$method])) {
// 命名范围的单独调用支持
return $this->scope($method, $args[0]);
} else {
StrackE(__CLASS__ . ':' . $method . L('_METHOD_NOT_EXIST_'), ErrorCode::METHOD_NOT_EXIST);
}
}
// 回调方法 初始化模型
protected function _initialize()
{
}
/**
* 对保存到数据库的数据进行处理
* @access protected
* @param mixed $data 要操作的数据
* @return array
* @throws \Exception
*/
protected function _facade($data)
{
// 检查数据字段合法性
if (!empty($this->fields)) {
if (!empty($this->options['field'])) {
$fields = $this->options['field'];
unset($this->options['field']);
if (is_string($fields)) {
$fields = explode(',', $fields);
}
} else {
$fields = $this->fields;
}
foreach ($data as $key => $val) {
if (!in_array($key, $fields, true)) {
if (!empty($this->options['strict'])) {
StrackE(L('_DATA_TYPE_INVALID_') . ':[' . $key . '=>' . $val . ']', ErrorCode::DATA_TYPE_INVALID);
}
unset($data[$key]);
} elseif (is_scalar($val)) {
// 字段类型检查 和 强制转换
$this->_parseType($data, $key);
}
}
}
// 安全过滤
if (!empty($this->options['filter'])) {
$data = array_map($this->options['filter'], $data);
unset($this->options['filter']);
}
$this->_before_write($data);
return $data;
}
/**
* 写入数据前的回调方法 包括新增和更新
* @param $data
*/
protected function _before_write(&$data)
{
}
/**
* 新增数据
* @access public
* @param mixed $data 数据
* @param array $options 表达式
* @param boolean $replace 是否replace
* @return bool|int|string
* @throws \Exception
*/
public function add($data = '', $options = [], $replace = false)
{
if (empty($data)) {
// 没有传递数据,获取当前数据对象的值
if (!empty($this->data)) {
$data = $this->data;
// 重置数据
$this->data = [];
} else {
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
}
// 数据处理
$data = $this->_facade($data);
// 分析表达式
$options = $this->_parseOptions($options);
if (false === $this->_before_insert($data, $options)) {
return false;
}
// 写入数据到数据库
$result = $this->db->insert($data, $options, $replace);
if (false !== $result && is_numeric($result)) {
$pk = $this->getPk();
// 增加复合主键支持
if (is_array($pk)) {
return $result;
}
$insertId = $this->getLastInsID();
if ($insertId) {
// 自增主键返回插入ID
$data[$pk] = $insertId;
if (false === $this->_after_insert($insertId, $pk, $data, $options)) {
return false;
}
return $insertId;
}
if (false === $this->_after_insert($insertId, $pk, $data, $options)) {
return false;
}
}
return $result;
}
/**
* 插入数据前的回调方法
* @param $data
* @param $options
*/
protected function _before_insert(&$data, $options)
{
}
/**
* 插入成功后的回调方法
* @param $pk
* @param $pkName
* @param $data
* @param $options
*/
protected function _after_insert($pk, $pkName, $data, $options)
{
}
/**
* 批量新增
* @param $dataList
* @param array $options
* @param bool $replace
* @return bool|int|string
* @throws \Exception
*/
public function addAll($dataList, $options = [], $replace = false)
{
if (empty($dataList)) {
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
// 数据处理
foreach ($dataList as $key => $data) {
$dataList[$key] = $this->_facade($data);
}
// 分析表达式
$options = $this->_parseOptions($options);
// 写入数据到数据库
$result = $this->db->insertAll($dataList, $options, $replace);
if (false !== $result) {
$insertId = $this->getLastInsID();
if ($insertId) {
return $insertId;
}
}
return $result;
}
/**
* 批量更新数据
* @param $allData
*/
public function saveAll($allData)
{
$sql = ''; //Sql
$pk = $this->getPk();
$tableName = $this->getTableName();
$lists = []; //记录集$lists
$ids = [];
foreach ($allData as $data) {
foreach ($data as $key => $value) {
if ($pk === $key) {
$ids[] = $value;
} else {
if (array_key_exists($key, $lists)) {
$lists[$key] .= sprintf("WHEN %u THEN '%s' ", $data[$pk], $value);
} else {
$lists[$key] = sprintf("WHEN %u THEN '%s' ", $data[$pk], $value);
}
}
}
}
foreach ($lists as $key => $value) {
$sql .= sprintf("`%s` = CASE `%s` %s END,", $key, $pk, $value);
}
$sql = sprintf('UPDATE %s SET %s WHERE %s IN ( %s )', $tableName, rtrim($sql, ','), $pk, implode(',', $ids));
M()->execute($sql);
unset($sql);
}
/**
* 通过Select方式添加记录
* @access public
* @param string $fields 要插入的数据表字段名
* @param string $table 要插入的数据表名
* @param array $options 表达式
* @return boolean
*/
public function selectAdd($fields = '', $table = '', $options = [])
{
// 分析表达式
$options = $this->_parseOptions($options);
// 写入数据到数据库
if (false === $result = $this->db->selectInsert($fields ?: $options['field'], $table ?: $this->getTableName(), $options)) {
// 数据库插入操作失败
$this->error = L('_OPERATION_WRONG_');
return false;
} else {
// 插入成功
return $result;
}
}
/**
* 保存数据
* @access public
* @param mixed $data 数据
* @param array $options 表达式
* @param bool $writeEvent
* @return bool|int
* @throws \Exception
*/
public function save($data = '', $options = [], $writeEvent = true)
{
if (empty($data)) {
// 没有传递数据,获取当前数据对象的值
if (!empty($this->data)) {
$data = $this->data;
// 重置数据
$this->data = [];
} else {
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
}
// 数据处理
$data = $this->_facade($data);
if (empty($data)) {
// 没有数据则不执行
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
// 分析表达式
$options = $this->_parseOptions($options);
$pk = $this->getPk();
if (!isset($options['where'])) {
// 如果存在主键数据 则自动作为更新条件
if (is_string($pk) && isset($data[$pk])) {
$where[$pk] = $data[$pk];
unset($data[$pk]);
} elseif (is_array($pk)) {
// 增加复合主键支持
foreach ($pk as $field) {
if (isset($data[$field])) {
$where[$field] = $data[$field];
} else {
// 如果缺少复合主键数据则不执行
$this->error = L('_OPERATION_WRONG_');
return false;
}
unset($data[$field]);
}
}
if (!isset($where)) {
// 如果没有任何更新条件则不执行
$this->error = L('_OPERATION_WRONG_');
return false;
} else {
$options['where'] = $where;
}
}
if (is_array($options['where']) && isset($options['where'][$pk])) {
$pkValue = $options['where'][$pk];
}
if (false === $this->_before_update($pk, $data, $options, $writeEvent)) {
return false;
}
$result = $this->db->update($data, $options);
if (false !== $result && is_numeric($result)) {
if (isset($pkValue)) {
$data[$pk] = $pkValue;
}
$this->_after_update($result, $pk, $data, $options, $writeEvent);
}
return $result;
}
/**
* 更新数据前的回调方法
* @param $pk
* @param $data
* @param $options
* @param $writeEvent
*/
protected function _before_update($pk, &$data, $options, $writeEvent)
{
$this->oldUpdateData = [];
$this->newUpdateData = [];
if ($options["model"] != "EventLog" && $writeEvent) {
$oldData = $this->where($options["where"])->find();
foreach ($data as $key => $value) {
if (false !== strpos($key, '->')) {
// json数据更新兼容取值,不精确到具体的值
[$indexKey, $name] = explode('->', $key, 2);
}else{
$indexKey = $key;
}
if ($oldData[$indexKey] != $value) {
//仅记录变化字段
$this->oldUpdateData[$indexKey] = $oldData[$indexKey];
$this->newUpdateData[$indexKey] = $value;
}
}
$this->oldUpdateKey = $oldData[$pk];
}
}
/**
* 更新成功后的回调方法
* @param $result
* @param $pkName
* @param $data
* @param $options
* @param $writeEvent
*/
protected function _after_update($result, $pkName, $data, $options, $writeEvent)
{
}
/**
* 删除数据
* @access public
* @param mixed $options 表达式
* @return mixed
*/
public function delete($options = [])
{
$where = [];
$pk = $this->getPk();
if (empty($options) && empty($this->options['where'])) {
// 如果删除条件为空 则删除当前数据对象所对应的记录
if (!empty($this->data) && isset($this->data[$pk])) {
return $this->delete($this->data[$pk]);
} else {
return false;
}
}
if (is_numeric($options) || is_string($options)) {
// 根据主键删除记录
if (strpos($options, ',')) {
$where[$pk] = ['IN', $options];
} else {
$where[$pk] = $options;
}
$this->options['where'] = $where;
}
// 根据复合主键删除记录
if (is_array($options) && (count($options) > 0) && is_array($pk)) {
$count = 0;
foreach (array_keys($options) as $key) {
if (is_int($key)) {
$count++;
}
}
if (count($pk) == $count) {
$i = 0;
foreach ($pk as $field) {
$where[$field] = $options[$i];
unset($options[$i++]);
}
$this->options['where'] = $where;
} else {
return false;
}
}
// 分析表达式
$options = $this->_parseOptions();
if (empty($options['where'])) {
// 如果条件为空 不进行删除操作 除非设置 1=1
return false;
}
if (is_array($options['where']) && isset($options['where'][$pk])) {
$pkValue = $options['where'][$pk];
}
if (false === $this->_before_delete($pk, $options)) {
return false;
}
$result = $this->db->delete($options);
if (false !== $result && is_numeric($result)) {
$data = [];
if (isset($pkValue)) {
$data[$pk] = $pkValue;
}
$this->_after_delete($result, $pk, $data, $options);
}
// 返回删除记录个数
return $result;
}
/**
* 删除数据前的回调方法
* @param $pk
* @param $options
*/
protected function _before_delete($pk, $options)
{
if ($options["model"] != "EventLog") {
$this->oldDeleteData = $this->where($options["where"])->select();
}
}
/**
* 删除成功后的回调方法
* @param $result
* @param $pkName
* @param $data
* @param $options
*/
protected function _after_delete($result, $pkName, $data, $options)
{
}
/**
* 查询数据集
* @access public
* @param array $options 表达式参数
* @return mixed
*/
public function select($options = [])
{
$where = [];
$pk = $this->getPk();
if (is_string($options) || is_numeric($options)) {
// 根据主键查询
if (strpos($options, ',')) {
$where[$pk] = ['IN', $options];
} else {
$where[$pk] = $options;
}
$this->options['where'] = $where;
} elseif (is_array($options) && (count($options) > 0) && is_array($pk)) {
// 根据复合主键查询
$count = 0;
foreach (array_keys($options) as $keyIndex) {
if (is_int($keyIndex)) {
$count++;
}
}
if (count($pk) == $count) {
$i = 0;
foreach ($pk as $field) {
$where[$field] = $options[$i];
unset($options[$i++]);
}
$this->options['where'] = $where;
} else {
return false;
}
} elseif (false === $options) {
// 用于子查询 不查询只返回SQL
$this->options['fetch_sql'] = true;
}
// 分析表达式
$options = $this->_parseOptions();
// 判断查询缓存
$key = "";
if (isset($options['cache'])) {
$cache = $options['cache'];
$key = is_string($cache['key']) ? $cache['key'] : md5(serialize($options));
$data = S($key, '', $cache);
if (false !== $data) {
return $data;
}
}
$resultSet = $this->db->select($options);
if (false === $resultSet) {
return false;
}
if (!empty($resultSet)) {
// 有查询结果
if (is_string($resultSet)) {
return $resultSet;
}
$resultSet = array_map([$this, '_read_data'], $resultSet);
$this->_after_select($resultSet, $options);
if (isset($options['index'])) {
// 对数据集进行索引
$index = explode(',', $options['index']);
$cols = [];
foreach ($resultSet as $result) {
$_key = $result[$index[0]];
if (isset($index[1]) && isset($result[$index[1]])) {
$cols[$_key] = $result[$index[1]];
} else {
$cols[$_key] = $result;
}
}
$resultSet = $cols;
}
}
if (isset($cache)) {
S($key, $resultSet, $cache);
}
return $resultSet;
}
// 查询成功后的回调方法
protected function _after_select(&$resultSet, $options)
{
}
/**
* 生成查询SQL 可用于子查询
* @access public
* @return string
*/
public function buildSql()
{