Completed
Push — 6.0 ( 41bbf5...66995e )
by liu
04:50
created

BaseQuery::pageSelect()   C

Complexity

Conditions 12
Paths 192

Size

Total Lines 59
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 156

Importance

Changes 9
Bugs 0 Features 0
Metric Value
cc 12
eloc 40
c 9
b 0
f 0
nc 192
nop 4
dl 0
loc 59
ccs 0
cts 35
cp 0
crap 156
rs 6.2

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
     * @return Paginator
586
     * @throws DbException
587
     */
588
    public function paginate($listRows = null, $simple = false): Paginator
589
    {
590
        if (is_int($simple)) {
591
            $total  = $simple;
592
            $simple = false;
593
        }
594
595
        $defaultConfig = [
596
            'query'     => [], //url额外参数
597
            'fragment'  => '', //url锚点
598
            'var_page'  => 'page', //分页变量
599
            'list_rows' => 15, //每页数量
600
        ];
601
602
        if (is_array($listRows)) {
603
            $config   = array_merge($defaultConfig, $listRows);
604
            $listRows = intval($config['list_rows']);
605
        } else {
606
            $config   = $defaultConfig;
607
            $listRows = intval($listRows ?: $config['list_rows']);
608
        }
609
610
        $page = isset($config['page']) ? (int) $config['page'] : Paginator::getCurrentPage($config['var_page']);
611
612
        $page = $page < 1 ? 1 : $page;
613
614
        $config['path'] = $config['path'] ?? Paginator::getCurrentPath();
615
616
        if (!isset($total) && !$simple) {
617
            $options = $this->getOptions();
618
619
            unset($this->options['order'], $this->options['limit'], $this->options['page'], $this->options['field']);
620
621
            $bind    = $this->bind;
622
            $total   = $this->count();
623
            $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

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

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

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

1276
        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...
1277
    }
1278
1279
    /**
1280
     * 通过Select方式插入记录
1281
     * @access public
1282
     * @param array  $fields 要插入的数据表字段名
1283
     * @param string $table  要插入的数据表名
1284
     * @return integer
1285
     * @throws PDOException
1286
     */
1287
    public function selectInsert(array $fields, string $table): int
1288
    {
1289
        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

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

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