Completed
Push — 6.0 ( 9a1cf1...43a634 )
by liu
05:00
created

BaseQuery::pageSelect()   F

Complexity

Conditions 11
Paths 576

Size

Total Lines 57
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 132

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 35
nc 576
nop 4
dl 0
loc 57
ccs 0
cts 29
cp 0
crap 132
rs 3.7388
c 1
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
declare (strict_types = 1);
12
13
namespace think\db;
14
15
use think\App;
16
use think\Collection;
17
use think\db\exception\BindParamException;
18
use think\db\exception\DataNotFoundException;
19
use think\db\exception\ModelNotFoundException;
20
use think\Exception;
21
use think\exception\DbException;
22
use think\exception\PDOException;
23
use think\Model;
24
use think\Paginator;
25
26
/**
27
 * 数据查询类
28
 */
29
class BaseQuery
30
{
31
    use concern\TimeFieldQuery;
32
    use concern\AggregateQuery;
33
    use concern\ModelRelationQuery;
34
    use concern\ResultOperation;
35
    use concern\Transaction;
36
    use concern\WhereQuery;
37
38
    /**
39
     * 当前数据库连接对象
40
     * @var Connection
41
     */
42
    protected $connection;
43
44
    /**
45
     * 当前数据表名称(不含前缀)
46
     * @var string
47
     */
48
    protected $name = '';
49
50
    /**
51
     * 当前数据表主键
52
     * @var string|array
53
     */
54
    protected $pk;
55
56
    /**
57
     * 当前数据表前缀
58
     * @var string
59
     */
60
    protected $prefix = '';
61
62
    /**
63
     * 当前查询参数
64
     * @var array
65
     */
66
    protected $options = [];
67
68
    /**
69
     * 架构函数
70
     * @access public
71
     * @param Connection $connection 数据库连接对象
72
     */
73
    public function __construct(Connection $connection)
74
    {
75
        $this->connection = $connection;
76
77
        $this->prefix = $this->connection->getConfig('prefix');
78
    }
79
80
    /**
81
     * 创建一个新的查询对象
82
     * @access public
83
     * @return BaseQuery
84
     */
85
    public function newQuery(): BaseQuery
86
    {
87
        $query = new static($this->connection);
88
89
        if ($this->model) {
90
            $query->model($this->model);
91
        }
92
93
        if (isset($this->options['table'])) {
94
            $query->table($this->options['table']);
95
        } else {
96
            $query->name($this->name);
97
        }
98
99
        return $query;
100
    }
101
102
    /**
103
     * 利用__call方法实现一些特殊的Model方法
104
     * @access public
105
     * @param string $method 方法名称
106
     * @param array  $args   调用参数
107
     * @return mixed
108
     * @throws DbException
109
     * @throws Exception
110
     */
111
    public function __call(string $method, array $args)
112
    {
113
        if (strtolower(substr($method, 0, 5)) == 'getby') {
114
            // 根据某个字段获取记录
115
            $field = App::parseName(substr($method, 5));
116
            return $this->where($field, '=', $args[0])->find();
117
        } elseif (strtolower(substr($method, 0, 10)) == 'getfieldby') {
118
            // 根据某个字段获取记录的某个值
119
            $name = App::parseName(substr($method, 10));
120
            return $this->where($name, '=', $args[0])->value($args[1]);
121
        } elseif (strtolower(substr($method, 0, 7)) == 'whereor') {
122
            $name = App::parseName(substr($method, 7));
123
            array_unshift($args, $name);
124
            return call_user_func_array([$this, 'whereOr'], $args);
125
        } elseif (strtolower(substr($method, 0, 5)) == 'where') {
126
            $name = App::parseName(substr($method, 5));
127
            array_unshift($args, $name);
128
            return call_user_func_array([$this, 'where'], $args);
129
        } elseif ($this->model && method_exists($this->model, 'scope' . $method)) {
130
            // 动态调用命名范围
131
            $method = 'scope' . $method;
132
            array_unshift($args, $this);
133
134
            call_user_func_array([$this->model, $method], $args);
135
            return $this;
136
        } else {
137
            throw new Exception('method not exist:' . static::class . '->' . $method);
138
        }
139
    }
140
141
    /**
142
     * 获取当前的数据库Connection对象
143
     * @access public
144
     * @return Connection
145
     */
146
    public function getConnection(): Connection
147
    {
148
        return $this->connection;
149
    }
150
151
    /**
152
     * 设置当前的数据库Connection对象
153
     * @access public
154
     * @param Connection $connection 数据库连接对象
155
     * @return $this
156
     */
157
    public function setConnection(Connection $connection)
158
    {
159
        $this->connection = $connection;
160
161
        return $this;
162
    }
163
164
    /**
165
     * 指定当前数据表名(不含前缀)
166
     * @access public
167
     * @param string $name 不含前缀的数据表名字
168
     * @return $this
169
     */
170
    public function name(string $name)
171
    {
172
        $this->name = $name;
173
        return $this;
174
    }
175
176
    /**
177
     * 获取当前的数据表名称
178
     * @access public
179
     * @return string
180
     */
181
    public function getName(): string
182
    {
183
        return $this->name ?: $this->model->getName();
184
    }
185
186
    /**
187
     * 获取数据库的配置参数
188
     * @access public
189
     * @param string $name 参数名称
190
     * @return mixed
191
     */
192
    public function getConfig(string $name = '')
193
    {
194
        return $this->connection->getConfig($name);
195
    }
196
197
    /**
198
     * 得到当前或者指定名称的数据表
199
     * @access public
200
     * @param string $name 不含前缀的数据表名字
201
     * @return mixed
202
     */
203
    public function getTable(string $name = '')
204
    {
205
        if (empty($name) && isset($this->options['table'])) {
206
            return $this->options['table'];
207
        }
208
209
        $name = $name ?: $this->name;
210
211
        return $this->prefix . App::parseName($name);
212
    }
213
214
    /**
215
     * 执行查询 返回数据集
216
     * @access public
217
     * @param string $sql  sql指令
218
     * @param array  $bind 参数绑定
219
     * @return array
220
     * @throws BindParamException
221
     * @throws PDOException
222
     */
223
    public function query(string $sql, array $bind = []): array
224
    {
225
        return $this->connection->query($this, $sql, $bind);
0 ignored issues
show
Bug introduced by
The method query() does not exist on think\db\Connection. Since it exists in all sub-types, consider adding an abstract or default implementation to think\db\Connection. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

225
        return $this->connection->/** @scrutinizer ignore-call */ query($this, $sql, $bind);
Loading history...
226
    }
227
228
    /**
229
     * 执行语句
230
     * @access public
231
     * @param string $sql  sql指令
232
     * @param array  $bind 参数绑定
233
     * @return int
234
     * @throws BindParamException
235
     * @throws PDOException
236
     */
237
    public function execute(string $sql, array $bind = []): int
238
    {
239
        return $this->connection->execute($this, $sql, $bind, true);
0 ignored issues
show
Bug introduced by
The method execute() does not exist on think\db\Connection. Since it exists in all sub-types, consider adding an abstract or default implementation to think\db\Connection. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

239
        return $this->connection->/** @scrutinizer ignore-call */ execute($this, $sql, $bind, true);
Loading history...
240
    }
241
242
    /**
243
     * 获取返回或者影响的记录数
244
     * @access public
245
     * @return integer
246
     */
247
    public function getNumRows(): int
248
    {
249
        return $this->connection->getNumRows();
0 ignored issues
show
Bug introduced by
The method getNumRows() does not exist on think\db\Connection. Since it exists in all sub-types, consider adding an abstract or default implementation to think\db\Connection. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

249
        return $this->connection->/** @scrutinizer ignore-call */ getNumRows();
Loading history...
250
    }
251
252
    /**
253
     * 获取最近一次查询的sql语句
254
     * @access public
255
     * @return string
256
     */
257
    public function getLastSql(): string
258
    {
259
        return $this->connection->getLastSql();
260
    }
261
262
    /**
263
     * 获取最近插入的ID
264
     * @access public
265
     * @param string $sequence 自增序列名
266
     * @return mixed
267
     */
268
    public function getLastInsID(string $sequence = null)
269
    {
270
        return $this->connection->getLastInsID($this, $sequence);
271
    }
272
273
    /**
274
     * 批处理执行SQL语句
275
     * 批处理的指令都认为是execute操作
276
     * @access public
277
     * @param array $sql SQL批处理指令
278
     * @return bool
279
     */
280
    public function batchQuery(array $sql = []): bool
281
    {
282
        return $this->connection->batchQuery($this, $sql);
0 ignored issues
show
Bug introduced by
The method batchQuery() does not exist on think\db\Connection. Since it exists in all sub-types, consider adding an abstract or default implementation to think\db\Connection. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

282
        return $this->connection->/** @scrutinizer ignore-call */ batchQuery($this, $sql);
Loading history...
283
    }
284
285
    /**
286
     * 得到某个字段的值
287
     * @access public
288
     * @param string $field   字段名
289
     * @param mixed  $default 默认值
290
     * @return mixed
291
     */
292
    public function value(string $field, $default = null)
293
    {
294
        return $this->connection->value($this, $field, $default);
295
    }
296
297
    /**
298
     * 得到某个列的数组
299
     * @access public
300
     * @param string $field 字段名 多个字段用逗号分隔
301
     * @param string $key   索引
302
     * @return array
303
     */
304
    public function column(string $field, string $key = ''): array
305
    {
306
        return $this->connection->column($this, $field, $key);
307
    }
308
309
    /**
310
     * 查询SQL组装 union
311
     * @access public
312
     * @param mixed   $union UNION
313
     * @param boolean $all   是否适用UNION ALL
314
     * @return $this
315
     */
316
    public function union($union, bool $all = false)
317
    {
318
        $this->options['union']['type'] = $all ? 'UNION ALL' : 'UNION';
319
320
        if (is_array($union)) {
321
            $this->options['union'] = array_merge($this->options['union'], $union);
322
        } else {
323
            $this->options['union'][] = $union;
324
        }
325
326
        return $this;
327
    }
328
329
    /**
330
     * 查询SQL组装 union all
331
     * @access public
332
     * @param mixed $union UNION数据
333
     * @return $this
334
     */
335
    public function unionAll($union)
336
    {
337
        return $this->union($union, true);
338
    }
339
340
    /**
341
     * 指定查询字段
342
     * @access public
343
     * @param mixed $field 字段信息
344
     * @return $this
345
     */
346
    public function field($field)
347
    {
348
        if (empty($field)) {
349
            return $this;
350
        } elseif ($field instanceof Raw) {
351
            $this->options['field'][] = $field;
352
            return $this;
353
        }
354
355
        if (is_string($field)) {
356
            if (preg_match('/[\<\'\"\(]/', $field)) {
357
                return $this->fieldRaw($field);
358
            }
359
360
            $field = array_map('trim', explode(',', $field));
361
        }
362
363
        if (true === $field) {
364
            // 获取全部字段
365
            $fields = $this->getTableFields();
0 ignored issues
show
Bug introduced by
The method getTableFields() does not exist on think\db\BaseQuery. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

365
            /** @scrutinizer ignore-call */ 
366
            $fields = $this->getTableFields();
Loading history...
366
            $field  = $fields ?: ['*'];
367
        }
368
369
        if (isset($this->options['field'])) {
370
            $field = array_merge((array) $this->options['field'], $field);
0 ignored issues
show
Bug introduced by
It seems like $field can also be of type think\db\BaseQuery; however, parameter $array2 of array_merge() does only seem to accept array|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

370
            $field = array_merge((array) $this->options['field'], /** @scrutinizer ignore-type */ $field);
Loading history...
371
        }
372
373
        $this->options['field'] = array_unique($field);
0 ignored issues
show
Bug introduced by
It seems like $field can also be of type think\db\BaseQuery; however, parameter $array of array_unique() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

373
        $this->options['field'] = array_unique(/** @scrutinizer ignore-type */ $field);
Loading history...
374
375
        return $this;
376
    }
377
378
    /**
379
     * 指定要排除的查询字段
380
     * @access public
381
     * @param array|string $field 要排除的字段
382
     * @return $this
383
     */
384
    public function withoutField($field)
385
    {
386
        if (empty($field)) {
387
            return $this;
388
        }
389
390
        if (is_string($field)) {
391
            $field = array_map('trim', explode(',', $field));
392
        }
393
394
        // 字段排除
395
        $fields = $this->getTableFields();
396
        $field  = $fields ? array_diff($fields, $field) : $field;
0 ignored issues
show
Bug introduced by
It seems like $fields can also be of type think\db\BaseQuery; however, parameter $array1 of array_diff() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

396
        $field  = $fields ? array_diff(/** @scrutinizer ignore-type */ $fields, $field) : $field;
Loading history...
397
398
        if (isset($this->options['field'])) {
399
            $field = array_merge((array) $this->options['field'], $field);
400
        }
401
402
        $this->options['field'] = array_unique($field);
403
404
        return $this;
405
    }
406
407
    /**
408
     * 指定其它数据表的查询字段
409
     * @access public
410
     * @param mixed   $field     字段信息
411
     * @param string  $tableName 数据表名
412
     * @param string  $prefix    字段前缀
413
     * @param string  $alias     别名前缀
414
     * @return $this
415
     */
416
    public function tableField($field, string $tableName, string $prefix = '', string $alias = '')
417
    {
418
        if (empty($field)) {
419
            return $this;
420
        }
421
422
        if (is_string($field)) {
423
            $field = array_map('trim', explode(',', $field));
424
        }
425
426
        if (true === $field) {
427
            // 获取全部字段
428
            $fields = $this->getTableFields($tableName);
429
            $field  = $fields ?: ['*'];
430
        }
431
432
        // 添加统一的前缀
433
        $prefix = $prefix ?: $tableName;
434
        foreach ($field as $key => &$val) {
435
            if (is_numeric($key) && $alias) {
436
                $field[$prefix . '.' . $val] = $alias . $val;
437
                unset($field[$key]);
438
            } elseif (is_numeric($key)) {
439
                $val = $prefix . '.' . $val;
440
            }
441
        }
442
443
        if (isset($this->options['field'])) {
444
            $field = array_merge((array) $this->options['field'], $field);
0 ignored issues
show
Bug introduced by
It seems like $field can also be of type think\db\BaseQuery; however, parameter $array2 of array_merge() does only seem to accept array|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

444
            $field = array_merge((array) $this->options['field'], /** @scrutinizer ignore-type */ $field);
Loading history...
445
        }
446
447
        $this->options['field'] = array_unique($field);
0 ignored issues
show
Bug introduced by
It seems like $field can also be of type think\db\BaseQuery; however, parameter $array of array_unique() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

447
        $this->options['field'] = array_unique(/** @scrutinizer ignore-type */ $field);
Loading history...
448
449
        return $this;
450
    }
451
452
    /**
453
     * 表达式方式指定查询字段
454
     * @access public
455
     * @param string $field 字段名
456
     * @return $this
457
     */
458
    public function fieldRaw(string $field)
459
    {
460
        $this->options['field'][] = new Raw($field);
461
462
        return $this;
463
    }
464
465
    /**
466
     * 设置数据
467
     * @access public
468
     * @param array $data 数据
469
     * @return $this
470
     */
471
    public function data(array $data)
472
    {
473
        $this->options['data'] = $data;
474
475
        return $this;
476
    }
477
478
    /**
479
     * 字段值增长
480
     * @access public
481
     * @param string  $field    字段名
482
     * @param float   $step     增长值
483
     * @param integer $lazyTime 延时时间(s)
484
     * @param string  $op       INC/DEC
485
     * @return $this
486
     */
487
    public function inc(string $field, float $step = 1, int $lazyTime = 0, string $op = 'INC')
488
    {
489
        if ($lazyTime > 0) {
490
            // 延迟写入
491
            $condition = $this->options['where'] ?? [];
492
493
            $guid = md5($this->getTable() . '_' . $field . '_' . serialize($condition));
494
            $step = $this->connection->lazyWrite($op, $guid, $step, $lazyTime);
495
496
            if (false === $step) {
497
                return $this;
498
            }
499
500
            $op = 'INC';
501
        }
502
503
        $this->options['data'][$field] = [$op, $step];
504
505
        return $this;
506
    }
507
508
    /**
509
     * 字段值减少
510
     * @access public
511
     * @param string  $field    字段名
512
     * @param float   $step     增长值
513
     * @param integer $lazyTime 延时时间(s)
514
     * @return $this
515
     */
516
    public function dec(string $field, float $step = 1, int $lazyTime = 0)
517
    {
518
        return $this->inc($field, $step, $lazyTime, 'DEC');
519
    }
520
521
    /**
522
     * 使用表达式设置数据
523
     * @access public
524
     * @param string $field 字段名
525
     * @param string $value 字段值
526
     * @return $this
527
     */
528
    public function exp(string $field, string $value)
529
    {
530
        $this->options['data'][$field] = new Raw($value);
531
        return $this;
532
    }
533
534
    /**
535
     * 去除查询参数
536
     * @access public
537
     * @param string $option 参数名 留空去除所有参数
538
     * @return $this
539
     */
540
    public function removeOption(string $option = '')
541
    {
542
        if ('' === $option) {
543
            $this->options = [];
544
            $this->bind    = [];
0 ignored issues
show
Bug Best Practice introduced by
The property bind does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
545
        } elseif (isset($this->options[$option])) {
546
            unset($this->options[$option]);
547
        }
548
549
        return $this;
550
    }
551
552
    /**
553
     * 指定查询数量
554
     * @access public
555
     * @param int $offset 起始位置
556
     * @param int $length 查询数量
557
     * @return $this
558
     */
559
    public function limit(int $offset, int $length = null)
560
    {
561
        $this->options['limit'] = $offset . ($length ? ',' . $length : '');
562
563
        return $this;
564
    }
565
566
    /**
567
     * 指定分页
568
     * @access public
569
     * @param int $page     页数
570
     * @param int $listRows 每页数量
571
     * @return $this
572
     */
573
    public function page(int $page, int $listRows = null)
574
    {
575
        $this->options['page'] = [$page, $listRows];
576
577
        return $this;
578
    }
579
580
    /**
581
     * 分页查询
582
     * @access public
583
     * @param int|array $listRows 每页数量 数组表示配置参数
584
     * @param int|bool  $simple   是否简洁模式或者总记录数
585
     * @param array     $config   配置参数
586
     * @return Paginator
587
     * @throws DbException
588
     */
589
    public function paginate($listRows = null, $simple = false, $config = [])
590
    {
591
        if (is_int($simple)) {
592
            $total  = $simple;
593
            $simple = false;
594
        }
595
596
        $defaultConfig = [
597
            'query'     => [], //url额外参数
598
            'fragment'  => '', //url锚点
599
            'var_page'  => 'page', //分页变量
600
            'list_rows' => 15, //每页数量
601
        ];
602
603
        if (is_array($listRows)) {
604
            $config   = array_merge($defaultConfig, $listRows);
605
            $listRows = intval($config['list_rows']);
606
        } else {
607
            $config   = array_merge($defaultConfig, $config);
608
            $listRows = intval($listRows ?: $config['list_rows']);
609
        }
610
611
        $page = isset($config['page']) ? (int) $config['page'] : Paginator::getCurrentPage($config['var_page']);
612
613
        $page = $page < 1 ? 1 : $page;
614
615
        $config['path'] = $config['path'] ?? Paginator::getCurrentPath();
616
617
        if (!isset($total) && !$simple) {
618
            $options = $this->getOptions();
619
620
            unset($this->options['order'], $this->options['limit'], $this->options['page'], $this->options['field']);
621
622
            $bind    = $this->bind;
623
            $total   = $this->count();
624
            $results = $this->options($options)->bind($bind)->page($page, $listRows)->select();
0 ignored issues
show
Bug introduced by
The method bind() does not exist on think\db\BaseQuery. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

624
            $results = $this->options($options)->/** @scrutinizer ignore-call */ bind($bind)->page($page, $listRows)->select();
Loading history...
625
        } elseif ($simple) {
626
            $results = $this->limit(($page - 1) * $listRows, $listRows + 1)->select();
627
            $total   = null;
628
        } else {
629
            $results = $this->page($page, $listRows)->select();
630
        }
631
632
        $this->removeOption('limit');
633
        $this->removeOption('page');
634
635
        return Paginator::make($results, $listRows, $page, $total, $simple, $config);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $total does not seem to be defined for all execution paths leading up to this point.
Loading history...
636
    }
637
638
    /**
639
     * 大数据分页查询
640
     * @access public
641
     * @param int|array $listRows 每页数量或者分页配置
642
     * @param int|bool  $simple   是否简洁模式或者总记录数
643
     * @param string    $key      索引键
644
     * @param string    $sort     排序 asc|desc
645
     * @return Paginator
646
     * @throws DbException
647
     */
648
    public function pageSelect($listRows = null, $simple = false, $key = null, $sort = null)
649
    {
650
        $defaultConfig = [
651
            'query'     => [], //url额外参数
652
            'fragment'  => '', //url锚点
653
            'var_page'  => 'page', //分页变量
654
            'list_rows' => 15, //每页数量
655
        ];
656
657
        if (is_array($listRows)) {
658
            $config = array_merge($defaultConfig, $listRows);
659
        } else {
660
            $config = $defaultConfig;
661
        }
662
663
        if (is_int($simple)) {
664
            $max    = $simple;
665
            $simple = false;
666
        } else {
667
            $max = null;
668
        }
669
670
        $listRows = is_int($listRows) ? $listRows : (int) $config['list_rows'];
671
672
        $page = isset($config['page']) ? (int) $config['page'] : Paginator::getCurrentPage($config['var_page']);
673
674
        $page = $page < 1 ? 1 : $page;
675
676
        $config['path'] = $config['path'] ?? Paginator::getCurrentPath();
677
678
        if (is_null($key)) {
679
            $key = $this->getPk();
680
        }
681
682
        if (is_null($sort)) {
683
            $order = $this->getOptions('order');
684
            if (!empty($order)) {
685
                $sort = $order[$key] ?? 'asc';
686
            } else {
687
                $this->order($key, 'desc');
688
            }
689
        }
690
691
        if ('asc' == $sort) {
692
            $this->where($key, '>', ($page - 1) * $listRows);
693
        } else {
694
            if (is_null($max)) {
695
                $data = $this->newQuery()->field($key)->where('1=1')->limit(1)->order($key, 'desc')->find();
696
                $max  = $data[$key];
697
            }
698
699
            $this->where($key, '<=', $max - ($page - 1) * $listRows);
700
        }
701
702
        $results = $this->limit($listRows)->select();
703
704
        return Paginator::make($results, $listRows, $page, $max, $simple, $config);
705
    }
706
707
    /**
708
     * 表达式方式指定当前操作的数据表
709
     * @access public
710
     * @param mixed $table 表名
711
     * @return $this
712
     */
713
    public function tableRaw(string $table)
714
    {
715
        $this->options['table'] = new Raw($table);
716
717
        return $this;
718
    }
719
720
    /**
721
     * 指定当前操作的数据表
722
     * @access public
723
     * @param mixed $table 表名
724
     * @return $this
725
     */
726
    public function table($table)
727
    {
728
        if (is_string($table)) {
729
            if (strpos($table, ')')) {
730
                // 子查询
731
            } elseif (false === strpos($table, ',')) {
732
                if (strpos($table, ' ')) {
733
                    list($item, $alias) = explode(' ', $table);
734
                    $table              = [];
735
                    $this->alias([$item => $alias]);
736
                    $table[$item] = $alias;
737
                }
738
            } else {
739
                $tables = explode(',', $table);
740
                $table  = [];
741
742
                foreach ($tables as $item) {
743
                    $item = trim($item);
744
                    if (strpos($item, ' ')) {
745
                        list($item, $alias) = explode(' ', $item);
746
                        $this->alias([$item => $alias]);
747
                        $table[$item] = $alias;
748
                    } else {
749
                        $table[] = $item;
750
                    }
751
                }
752
            }
753
        } elseif (is_array($table)) {
754
            $tables = $table;
755
            $table  = [];
756
757
            foreach ($tables as $key => $val) {
758
                if (is_numeric($key)) {
759
                    $table[] = $val;
760
                } else {
761
                    $this->alias([$key => $val]);
762
                    $table[$key] = $val;
763
                }
764
            }
765
        }
766
767
        $this->options['table'] = $table;
768
769
        return $this;
770
    }
771
772
    /**
773
     * USING支持 用于多表删除
774
     * @access public
775
     * @param mixed $using USING
776
     * @return $this
777
     */
778
    public function using($using)
779
    {
780
        $this->options['using'] = $using;
781
        return $this;
782
    }
783
784
    /**
785
     * 存储过程调用
786
     * @access public
787
     * @param bool $procedure 是否为存储过程查询
788
     * @return $this
789
     */
790
    public function procedure(bool $procedure = true)
791
    {
792
        $this->options['procedure'] = $procedure;
793
        return $this;
794
    }
795
796
    /**
797
     * 指定排序 order('id','desc') 或者 order(['id'=>'desc','create_time'=>'desc'])
798
     * @access public
799
     * @param string|array|Raw $field 排序字段
800
     * @param string           $order 排序
801
     * @return $this
802
     */
803
    public function order($field, string $order = '')
804
    {
805
        if (empty($field)) {
806
            return $this;
807
        } elseif ($field instanceof Raw) {
808
            $this->options['order'][] = $field;
809
            return $this;
810
        }
811
812
        if (is_string($field)) {
813
            if (!empty($this->options['via'])) {
814
                $field = $this->options['via'] . '.' . $field;
815
            }
816
            if (strpos($field, ',')) {
817
                $field = array_map('trim', explode(',', $field));
818
            } else {
819
                $field = empty($order) ? $field : [$field => $order];
820
            }
821
        } elseif (!empty($this->options['via'])) {
822
            foreach ($field as $key => $val) {
823
                if (is_numeric($key)) {
824
                    $field[$key] = $this->options['via'] . '.' . $val;
825
                } else {
826
                    $field[$this->options['via'] . '.' . $key] = $val;
827
                    unset($field[$key]);
828
                }
829
            }
830
        }
831
832
        if (!isset($this->options['order'])) {
833
            $this->options['order'] = [];
834
        }
835
836
        if (is_array($field)) {
837
            $this->options['order'] = array_merge($this->options['order'], $field);
838
        } else {
839
            $this->options['order'][] = $field;
840
        }
841
842
        return $this;
843
    }
844
845
    /**
846
     * 表达式方式指定Field排序
847
     * @access public
848
     * @param string $field 排序字段
849
     * @param array  $bind  参数绑定
850
     * @return $this
851
     */
852
    public function orderRaw(string $field, array $bind = [])
853
    {
854
        if (!empty($bind)) {
855
            $this->bindParams($field, $bind);
0 ignored issues
show
Bug introduced by
The method bindParams() does not exist on think\db\BaseQuery. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

855
            $this->/** @scrutinizer ignore-call */ 
856
                   bindParams($field, $bind);
Loading history...
856
        }
857
858
        $this->options['order'][] = new Raw($field);
859
860
        return $this;
861
    }
862
863
    /**
864
     * 指定Field排序 orderField('id',[1,2,3],'desc')
865
     * @access public
866
     * @param string $field  排序字段
867
     * @param array  $values 排序值
868
     * @param string $order  排序 desc/asc
869
     * @return $this
870
     */
871
    public function orderField(string $field, array $values, string $order = '')
872
    {
873
        if (!empty($values)) {
874
            $values['sort'] = $order;
875
876
            $this->options['order'][$field] = $values;
877
        }
878
879
        return $this;
880
    }
881
882
    /**
883
     * 随机排序
884
     * @access public
885
     * @return $this
886
     */
887
    public function orderRand()
888
    {
889
        $this->options['order'][] = '[rand]';
890
        return $this;
891
    }
892
893
    /**
894
     * 查询缓存
895
     * @access public
896
     * @param mixed             $key    缓存key
897
     * @param integer|\DateTime $expire 缓存有效期
898
     * @param string            $tag    缓存标签
899
     * @return $this
900
     */
901
    public function cache($key = true, $expire = null, string $tag = null)
902
    {
903
        if (false === $key) {
904
            return $this;
905
        }
906
907
        if ($key instanceof \DateTimeInterface || $key instanceof \DateInterval || (is_int($key) && is_null($expire))) {
908
            $expire = $key;
909
            $key    = true;
910
        }
911
912
        $this->options['cache'] = [$key, $expire, $tag];
913
914
        return $this;
915
    }
916
917
    /**
918
     * 指定group查询
919
     * @access public
920
     * @param string|array $group GROUP
921
     * @return $this
922
     */
923
    public function group($group)
924
    {
925
        $this->options['group'] = $group;
926
        return $this;
927
    }
928
929
    /**
930
     * 指定having查询
931
     * @access public
932
     * @param string $having having
933
     * @return $this
934
     */
935
    public function having(string $having)
936
    {
937
        $this->options['having'] = $having;
938
        return $this;
939
    }
940
941
    /**
942
     * 指定查询lock
943
     * @access public
944
     * @param bool|string $lock 是否lock
945
     * @return $this
946
     */
947
    public function lock($lock = false)
948
    {
949
        $this->options['lock'] = $lock;
950
951
        if ($lock) {
952
            $this->options['master'] = true;
953
        }
954
955
        return $this;
956
    }
957
958
    /**
959
     * 指定distinct查询
960
     * @access public
961
     * @param bool $distinct 是否唯一
962
     * @return $this
963
     */
964
    public function distinct(bool $distinct = true)
965
    {
966
        $this->options['distinct'] = $distinct;
967
        return $this;
968
    }
969
970
    /**
971
     * 指定数据表别名
972
     * @access public
973
     * @param array|string $alias 数据表别名
974
     * @return $this
975
     */
976
    public function alias($alias)
977
    {
978
        if (is_array($alias)) {
979
            $this->options['alias'] = $alias;
980
        } else {
981
            $table = $this->getTable();
982
983
            $this->options['alias'][$table] = $alias;
984
        }
985
986
        return $this;
987
    }
988
989
    /**
990
     * 指定强制索引
991
     * @access public
992
     * @param string $force 索引名称
993
     * @return $this
994
     */
995
    public function force(string $force)
996
    {
997
        $this->options['force'] = $force;
998
        return $this;
999
    }
1000
1001
    /**
1002
     * 查询注释
1003
     * @access public
1004
     * @param string $comment 注释
1005
     * @return $this
1006
     */
1007
    public function comment(string $comment)
1008
    {
1009
        $this->options['comment'] = $comment;
1010
        return $this;
1011
    }
1012
1013
    /**
1014
     * 获取执行的SQL语句而不进行实际的查询
1015
     * @access public
1016
     * @param bool $fetch 是否返回sql
1017
     * @return $this|Fetch
1018
     */
1019
    public function fetchSql(bool $fetch = true)
1020
    {
1021
        $this->options['fetch_sql'] = $fetch;
1022
1023
        if ($fetch) {
1024
            return new Fetch($this);
1025
        }
1026
1027
        return $this;
1028
    }
1029
1030
    /**
1031
     * 设置从主服务器读取数据
1032
     * @access public
1033
     * @param bool $readMaster 是否从主服务器读取
1034
     * @return $this
1035
     */
1036
    public function master(bool $readMaster = true)
1037
    {
1038
        $this->options['master'] = $readMaster;
1039
        return $this;
1040
    }
1041
1042
    /**
1043
     * 设置是否严格检查字段名
1044
     * @access public
1045
     * @param bool $strict 是否严格检查字段
1046
     * @return $this
1047
     */
1048
    public function strict(bool $strict = true)
1049
    {
1050
        $this->options['strict'] = $strict;
1051
        return $this;
1052
    }
1053
1054
    /**
1055
     * 设置自增序列名
1056
     * @access public
1057
     * @param string $sequence 自增序列名
1058
     * @return $this
1059
     */
1060
    public function sequence(string $sequence = null)
1061
    {
1062
        $this->options['sequence'] = $sequence;
1063
        return $this;
1064
    }
1065
1066
    /**
1067
     * 设置是否REPLACE
1068
     * @access public
1069
     * @param bool $replace 是否使用REPLACE写入数据
1070
     * @return $this
1071
     */
1072
    public function replace(bool $replace = true)
1073
    {
1074
        $this->options['replace'] = $replace;
1075
        return $this;
1076
    }
1077
1078
    /**
1079
     * 设置当前查询所在的分区
1080
     * @access public
1081
     * @param string|array $partition 分区名称
1082
     * @return $this
1083
     */
1084
    public function partition($partition)
1085
    {
1086
        $this->options['partition'] = $partition;
1087
        return $this;
1088
    }
1089
1090
    /**
1091
     * 设置DUPLICATE
1092
     * @access public
1093
     * @param array|string|Raw $duplicate DUPLICATE信息
1094
     * @return $this
1095
     */
1096
    public function duplicate($duplicate)
1097
    {
1098
        $this->options['duplicate'] = $duplicate;
1099
        return $this;
1100
    }
1101
1102
    /**
1103
     * 设置查询的额外参数
1104
     * @access public
1105
     * @param string $extra 额外信息
1106
     * @return $this
1107
     */
1108
    public function extra(string $extra)
1109
    {
1110
        $this->options['extra'] = $extra;
1111
        return $this;
1112
    }
1113
1114
    /**
1115
     * 设置JSON字段信息
1116
     * @access public
1117
     * @param array $json  JSON字段
1118
     * @param bool  $assoc 是否取出数组
1119
     * @return $this
1120
     */
1121
    public function json(array $json = [], bool $assoc = false)
1122
    {
1123
        $this->options['json']       = $json;
1124
        $this->options['json_assoc'] = $assoc;
1125
        return $this;
1126
    }
1127
1128
    /**
1129
     * 指定数据表主键
1130
     * @access public
1131
     * @param string $pk 主键
1132
     * @return $this
1133
     */
1134
    public function pk(string $pk)
1135
    {
1136
        $this->pk = $pk;
1137
        return $this;
1138
    }
1139
1140
    /**
1141
     * 获取当前数据表的主键
1142
     * @access public
1143
     * @return string|array
1144
     */
1145
    public function getPk()
1146
    {
1147
        if (empty($this->pk)) {
1148
            $this->pk = $this->connection->getPk($this->getTable());
0 ignored issues
show
Bug introduced by
The method getPk() does not exist on think\db\Connection. Since it exists in all sub-types, consider adding an abstract or default implementation to think\db\Connection. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1148
            /** @scrutinizer ignore-call */ 
1149
            $this->pk = $this->connection->getPk($this->getTable());
Loading history...
1149
        }
1150
1151
        return $this->pk;
1152
    }
1153
1154
    /**
1155
     * 查询参数批量赋值
1156
     * @access protected
1157
     * @param array $options 表达式参数
1158
     * @return $this
1159
     */
1160
    protected function options(array $options)
1161
    {
1162
        $this->options = $options;
1163
        return $this;
1164
    }
1165
1166
    /**
1167
     * 获取当前的查询参数
1168
     * @access public
1169
     * @param string $name 参数名
1170
     * @return mixed
1171
     */
1172
    public function getOptions(string $name = '')
1173
    {
1174
        if ('' === $name) {
1175
            return $this->options;
1176
        }
1177
1178
        return $this->options[$name] ?? null;
1179
    }
1180
1181
    /**
1182
     * 设置当前的查询参数
1183
     * @access public
1184
     * @param string $option 参数名
1185
     * @param mixed  $value  参数值
1186
     * @return $this
1187
     */
1188
    public function setOption(string $option, $value)
1189
    {
1190
        $this->options[$option] = $value;
1191
        return $this;
1192
    }
1193
1194
    /**
1195
     * 设置当前字段添加的表别名
1196
     * @access public
1197
     * @param string $via 临时表别名
1198
     * @return $this
1199
     */
1200
    public function via(string $via = '')
1201
    {
1202
        $this->options['via'] = $via;
1203
1204
        return $this;
1205
    }
1206
1207
    /**
1208
     * 保存记录 自动判断insert或者update
1209
     * @access public
1210
     * @param array $data        数据
1211
     * @param bool  $forceInsert 是否强制insert
1212
     * @return integer
1213
     */
1214
    public function save(array $data = [], bool $forceInsert = false)
1215
    {
1216
        if ($forceInsert) {
1217
            return $this->insert($data);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->insert($data) also could return the type string which is incompatible with the documented return type integer.
Loading history...
1218
        }
1219
1220
        $this->options['data'] = array_merge($this->options['data'] ?? [], $data);
1221
1222
        if (!empty($this->options['where'])) {
1223
            $isUpdate = true;
1224
        } else {
1225
            $isUpdate = $this->parseUpdateData($this->options['data']);
1226
        }
1227
1228
        return $isUpdate ? $this->update() : $this->insert();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $isUpdate ? $this...ate() : $this->insert() also could return the type string which is incompatible with the documented return type integer.
Loading history...
1229
    }
1230
1231
    /**
1232
     * 插入记录
1233
     * @access public
1234
     * @param array   $data         数据
1235
     * @param boolean $getLastInsID 返回自增主键
1236
     * @return integer|string
1237
     */
1238
    public function insert(array $data = [], bool $getLastInsID = false)
1239
    {
1240
        if (!empty($data)) {
1241
            $this->options['data'] = $data;
1242
        }
1243
1244
        return $this->connection->insert($this, $getLastInsID);
1245
    }
1246
1247
    /**
1248
     * 插入记录并获取自增ID
1249
     * @access public
1250
     * @param array $data 数据
1251
     * @return integer|string
1252
     */
1253
    public function insertGetId(array $data)
1254
    {
1255
        return $this->insert($data, true);
1256
    }
1257
1258
    /**
1259
     * 批量插入记录
1260
     * @access public
1261
     * @param array   $dataSet 数据集
1262
     * @param integer $limit   每次写入数据限制
1263
     * @return integer
1264
     */
1265
    public function insertAll(array $dataSet = [], int $limit = 0): int
1266
    {
1267
        if (empty($dataSet)) {
1268
            $dataSet = $this->options['data'] ?? [];
1269
        }
1270
1271
        if (empty($limit) && !empty($this->options['limit']) && is_numeric($this->options['limit'])) {
1272
            $limit = (int) $this->options['limit'];
1273
        }
1274
1275
        return $this->connection->insertAll($this, $dataSet, $limit);
0 ignored issues
show
Unused Code introduced by
The call to think\db\Connection::insertAll() has too many arguments starting with $limit. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1275
        return $this->connection->/** @scrutinizer ignore-call */ insertAll($this, $dataSet, $limit);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
1276
    }
1277
1278
    /**
1279
     * 通过Select方式插入记录
1280
     * @access public
1281
     * @param array  $fields 要插入的数据表字段名
1282
     * @param string $table  要插入的数据表名
1283
     * @return integer
1284
     * @throws PDOException
1285
     */
1286
    public function selectInsert(array $fields, string $table): int
1287
    {
1288
        return $this->connection->selectInsert($this, $fields, $table);
0 ignored issues
show
Bug introduced by
The method selectInsert() does not exist on think\db\Connection. Did you maybe mean select()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1288
        return $this->connection->/** @scrutinizer ignore-call */ selectInsert($this, $fields, $table);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1289
    }
1290
1291
    /**
1292
     * 更新记录
1293
     * @access public
1294
     * @param mixed $data 数据
1295
     * @return integer
1296
     * @throws Exception
1297
     * @throws PDOException
1298
     */
1299
    public function update(array $data = []): int
1300
    {
1301
        if (!empty($data)) {
1302
            $this->options['data'] = array_merge($this->options['data'] ?? [], $data);
1303
        }
1304
1305
        if (empty($this->options['where'])) {
1306
            $this->parseUpdateData($this->options['data']);
1307
        }
1308
1309
        if (empty($this->options['where']) && $this->model) {
1310
            $this->where($this->model->getWhere());
1311
        }
1312
1313
        if (empty($this->options['where'])) {
1314
            // 如果没有任何更新条件则不执行
1315
            throw new Exception('miss update condition');
1316
        }
1317
1318
        return $this->connection->update($this);
1319
    }
1320
1321
    /**
1322
     * 删除记录
1323
     * @access public
1324
     * @param mixed $data 表达式 true 表示强制删除
1325
     * @return int
1326
     * @throws Exception
1327
     * @throws PDOException
1328
     */
1329
    public function delete($data = null): int
1330
    {
1331
        if (!is_null($data) && true !== $data) {
1332
            // AR模式分析主键条件
1333
            $this->parsePkWhere($data);
1334
        }
1335
1336
        if (empty($this->options['where']) && $this->model) {
1337
            $this->where($this->model->getWhere());
1338
        }
1339
1340
        if (true !== $data && empty($this->options['where'])) {
1341
            // 如果条件为空 不进行删除操作 除非设置 1=1
1342
            throw new Exception('delete without condition');
1343
        }
1344
1345
        if (!empty($this->options['soft_delete'])) {
1346
            // 软删除
1347
            list($field, $condition) = $this->options['soft_delete'];
1348
            if ($condition) {
1349
                unset($this->options['soft_delete']);
1350
                $this->options['data'] = [$field => $condition];
1351
1352
                return $this->connection->update($this);
1353
            }
1354
        }
1355
1356
        $this->options['data'] = $data;
1357
1358
        return $this->connection->delete($this);
1359
    }
1360
1361
    /**
1362
     * 查找记录
1363
     * @access public
1364
     * @param mixed $data 数据
1365
     * @return Collection
1366
     * @throws DbException
1367
     * @throws ModelNotFoundException
1368
     * @throws DataNotFoundException
1369
     */
1370
    public function select($data = null): Collection
1371
    {
1372
        if (!is_null($data)) {
1373
            // 主键条件分析
1374
            $this->parsePkWhere($data);
1375
        }
1376
1377
        $resultSet = $this->connection->select($this);
1378
1379
        // 返回结果处理
1380
        if (!empty($this->options['fail']) && count($resultSet) == 0) {
1381
            $this->throwNotFound();
1382
        }
1383
1384
        // 数据列表读取后的处理
1385
        if (!empty($this->model)) {
1386
            // 生成模型对象
1387
            $resultSet = $this->resultSetToModelCollection($resultSet);
1388
        } else {
1389
            $this->resultSet($resultSet);
1390
        }
1391
1392
        return $resultSet;
1393
    }
1394
1395
    /**
1396
     * 查找单条记录
1397
     * @access public
1398
     * @param mixed $data 查询数据
1399
     * @return array|Model|null
1400
     * @throws DbException
1401
     * @throws ModelNotFoundException
1402
     * @throws DataNotFoundException
1403
     */
1404
    public function find($data = null)
1405
    {
1406
        if (!is_null($data)) {
1407
            // AR模式分析主键条件
1408
            $this->parsePkWhere($data);
1409
        }
1410
1411
        if (empty($this->options['where'])) {
1412
            $result = [];
1413
        } else {
1414
            $result = $this->connection->find($this);
1415
        }
1416
1417
        // 数据处理
1418
        if (empty($result)) {
1419
            return $this->resultToEmpty();
1420
        }
1421
1422
        if (!empty($this->model)) {
1423
            // 返回模型对象
1424
            $this->resultToModel($result, $this->options);
1425
        } else {
1426
            $this->result($result);
1427
        }
1428
1429
        return $result;
1430
    }
1431
1432
    /**
1433
     * 分批数据返回处理
1434
     * @access public
1435
     * @param integer      $count    每次处理的数据数量
1436
     * @param callable     $callback 处理回调方法
1437
     * @param string|array $column   分批处理的字段名
1438
     * @param string       $order    字段排序
1439
     * @return bool
1440
     * @throws DbException
1441
     */
1442
    public function chunk(int $count, callable $callback, $column = null, string $order = 'asc'): bool
1443
    {
1444
        $options = $this->getOptions();
1445
        $column  = $column ?: $this->getPk();
1446
1447
        if (isset($options['order'])) {
1448
            unset($options['order']);
1449
        }
1450
1451
        $bind = $this->bind;
1452
1453
        if (is_array($column)) {
1454
            $times = 1;
1455
            $query = $this->options($options)->page($times, $count);
1456
        } else {
1457
            $query = $this->options($options)->limit($count);
1458
1459
            if (strpos($column, '.')) {
1460
                list($alias, $key) = explode('.', $column);
1461
            } else {
1462
                $key = $column;
1463
            }
1464
        }
1465
1466
        $resultSet = $query->order($column, $order)->select();
1467
1468
        while (count($resultSet) > 0) {
1469
            if (false === call_user_func($callback, $resultSet)) {
1470
                return false;
1471
            }
1472
1473
            if (isset($times)) {
1474
                $times++;
1475
                $query = $this->options($options)->page($times, $count);
1476
            } else {
1477
                $end    = $resultSet->pop();
1478
                $lastId = is_array($end) ? $end[$key] : $end->getData($key);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $key does not seem to be defined for all execution paths leading up to this point.
Loading history...
1479
1480
                $query = $this->options($options)
1481
                    ->limit($count)
1482
                    ->where($column, 'asc' == strtolower($order) ? '>' : '<', $lastId);
1483
            }
1484
1485
            $resultSet = $query->bind($bind)->order($column, $order)->select();
1486
        }
1487
1488
        return true;
1489
    }
1490
1491
    /**
1492
     * 创建子查询SQL
1493
     * @access public
1494
     * @param bool $sub 是否添加括号
1495
     * @return string
1496
     * @throws DbException
1497
     */
1498
    public function buildSql(bool $sub = true): string
1499
    {
1500
        return $sub ? '( ' . $this->fetchSql()->select() . ' )' : $this->fetchSql()->select();
1501
    }
1502
1503
    /**
1504
     * 分析表达式(可用于查询或者写入操作)
1505
     * @access public
1506
     * @return array
1507
     */
1508
    public function parseOptions(): array
1509
    {
1510
        $options = $this->getOptions();
1511
1512
        // 获取数据表
1513
        if (empty($options['table'])) {
1514
            $options['table'] = $this->getTable();
1515
        }
1516
1517
        if (!isset($options['where'])) {
1518
            $options['where'] = [];
1519
        } elseif (isset($options['view'])) {
1520
            // 视图查询条件处理
1521
            $this->parseView($options);
0 ignored issues
show
Bug introduced by
The method parseView() does not exist on think\db\BaseQuery. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1521
            $this->/** @scrutinizer ignore-call */ 
1522
                   parseView($options);
Loading history...
1522
        }
1523
1524
        if (!isset($options['field'])) {
1525
            $options['field'] = '*';
1526
        }
1527
1528
        foreach (['data', 'order', 'join', 'union'] as $name) {
1529
            if (!isset($options[$name])) {
1530
                $options[$name] = [];
1531
            }
1532
        }
1533
1534
        if (!isset($options['strict'])) {
1535
            $options['strict'] = $this->connection->getConfig('fields_strict');
1536
        }
1537
1538
        foreach (['master', 'lock', 'fetch_sql', 'array', 'distinct', 'procedure'] as $name) {
1539
            if (!isset($options[$name])) {
1540
                $options[$name] = false;
1541
            }
1542
        }
1543
1544
        foreach (['group', 'having', 'limit', 'force', 'comment', 'partition', 'duplicate', 'extra'] as $name) {
1545
            if (!isset($options[$name])) {
1546
                $options[$name] = '';
1547
            }
1548
        }
1549
1550
        if (isset($options['page'])) {
1551
            // 根据页数计算limit
1552
            list($page, $listRows) = $options['page'];
1553
            $page                  = $page > 0 ? $page : 1;
1554
            $listRows              = $listRows ?: (is_numeric($options['limit']) ? $options['limit'] : 20);
1555
            $offset                = $listRows * ($page - 1);
1556
            $options['limit']      = $offset . ',' . $listRows;
1557
        }
1558
1559
        $this->options = $options;
1560
1561
        return $options;
1562
    }
1563
1564
    /**
1565
     * 分析数据是否存在更新条件
1566
     * @access public
1567
     * @param array $data 数据
1568
     * @return bool
1569
     * @throws Exception
1570
     */
1571
    public function parseUpdateData(&$data): bool
1572
    {
1573
        $pk       = $this->getPk();
1574
        $isUpdate = false;
1575
        // 如果存在主键数据 则自动作为更新条件
1576
        if (is_string($pk) && isset($data[$pk])) {
1577
            $this->where($pk, '=', $data[$pk]);
1578
            $this->options['key'] = $data[$pk];
1579
            unset($data[$pk]);
1580
            $isUpdate = true;
1581
        } elseif (is_array($pk)) {
1582
            foreach ($pk as $field) {
1583
                if (isset($data[$field])) {
1584
                    $this->where($field, '=', $data[$field]);
1585
                    $isUpdate = true;
1586
                } else {
1587
                    // 如果缺少复合主键数据则不执行
1588
                    throw new Exception('miss complex primary data');
1589
                }
1590
                unset($data[$field]);
1591
            }
1592
        }
1593
1594
        return $isUpdate;
1595
    }
1596
1597
    /**
1598
     * 把主键值转换为查询条件 支持复合主键
1599
     * @access public
1600
     * @param array|string $data 主键数据
1601
     * @return void
1602
     * @throws Exception
1603
     */
1604
    public function parsePkWhere($data): void
1605
    {
1606
        $pk = $this->getPk();
1607
1608
        if (is_string($pk)) {
1609
            // 获取数据表
1610
            if (empty($this->options['table'])) {
1611
                $this->options['table'] = $this->getTable();
1612
            }
1613
1614
            $table = is_array($this->options['table']) ? key($this->options['table']) : $this->options['table'];
1615
1616
            if (!empty($this->options['alias'][$table])) {
1617
                $alias = $this->options['alias'][$table];
1618
            }
1619
1620
            $key = isset($alias) ? $alias . '.' . $pk : $pk;
1621
            // 根据主键查询
1622
            if (is_array($data)) {
1623
                $this->where($key, 'in', $data);
1624
            } else {
1625
                $this->where($key, '=', $data);
1626
                $this->options['key'] = $data;
1627
            }
1628
        }
1629
    }
1630
1631
    /**
1632
     * 获取模型的更新条件
1633
     * @access protected
1634
     * @param array $options 查询参数
1635
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
1636
    protected function getModelUpdateCondition(array $options)
1637
    {
1638
        return $options['where']['AND'] ?? null;
1639
    }
1640
}
1641