Test Failed
Push — 6.0 ( 85d292...54779c )
by liu
08:11
created

BaseQuery::pageSelect()   C

Complexity

Conditions 11
Paths 288

Size

Total Lines 48
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 132

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 11
eloc 30
nc 288
nop 4
dl 0
loc 48
ccs 0
cts 28
cp 0
crap 132
rs 5.3833
c 3
b 0
f 0

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

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

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

1265
        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...
1266
    }
1267
1268
    /**
1269
     * 通过Select方式插入记录
1270
     * @access public
1271
     * @param array  $fields 要插入的数据表字段名
1272
     * @param string $table  要插入的数据表名
1273
     * @return integer
1274
     * @throws PDOException
1275
     */
1276
    public function selectInsert(array $fields, string $table): int
1277
    {
1278
        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

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

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