Completed
Push — 6.0 ( 939c37...c13f16 )
by liu
04:39
created

BaseQuery::more()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 18
c 1
b 0
f 0
nc 3
nop 4
dl 0
loc 27
ccs 0
cts 15
cp 0
crap 30
rs 9.3554
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);
371
        }
372
373
        $this->options['field'] = array_unique($field);
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);
445
        }
446
447
        $this->options['field'] = array_unique($field);
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
     * @return Paginator
644
     * @throws DbException
645
     */
646
    public function paginateX($listRows = null, string $key = null, string $sort = null): Paginator
647
    {
648
        $defaultConfig = [
649
            'query'     => [], //url额外参数
650
            'fragment'  => '', //url锚点
651
            'var_page'  => 'page', //分页变量
652
            'list_rows' => 15, //每页数量
653
        ];
654
655
        $config   = is_array($listRows) ? array_merge($defaultConfig, $listRows) : $defaultConfig;
656
        $listRows = is_int($listRows) ? $listRows : (int) $config['list_rows'];
657
        $page     = isset($config['page']) ? (int) $config['page'] : Paginator::getCurrentPage($config['var_page']);
658
        $page     = $page < 1 ? 1 : $page;
659
660
        $config['path'] = $config['path'] ?? Paginator::getCurrentPath();
661
662
        $key     = $key ?: $this->getPk();
663
        $options = $this->getOptions();
664
665
        if (is_null($sort)) {
666
            $order = $options['order'] ?? '';
667
            if (!empty($order)) {
668
                $sort = $order[$key] ?? 'desc';
669
            } else {
670
                $this->order($key, 'desc');
671
                $sort = 'desc';
672
            }
673
        } else {
674
            $this->order($key, $sort);
675
        }
676
677
        $newOption = $options;
678
        unset($newOption['field'], $newOption['page']);
679
680
        $data = $this->newQuery()
681
            ->options($newOption)
682
            ->field($key)
683
            ->where(true)
684
            ->order($key, $sort)
685
            ->limit(1)
686
            ->find();
687
688
        $result = $data[$key];
689
690
        if (is_numeric($result)) {
691
            $lastId = 'asc' == $sort ? ($result - 1) + ($page - 1) * $listRows : ($result + 1) - ($page - 1) * $listRows;
692
        } else {
693
            throw new Exception('not support type');
694
        }
695
696
        $results = $this->when($lastId, function ($query) use ($key, $sort, $lastId) {
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
697
            $query->where($key, 'asc' == $sort ? '>' : '<', $lastId);
698
        })
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
699
            ->limit($listRows)
700
            ->select();
701
702
        $this->options($options);
703
704
        return Paginator::make($results, $listRows, $page, null, true, $config);
705
    }
706
707
    /**
708
     * 根据最后ID查询更多N个数据
709
     * @access public
710
     * @param int        $limit  LIMIT
711
     * @param int|string $lastId LastId
712
     * @param string     $key    分页索引键 默认为主键
713
     * @param string     $sort   索引键排序 asc|desc
714
     * @return array
715
     * @throws DbException
716
     */
717
    public function more(int $limit, $lastId = null, string $key = null, string $sort = null): array
718
    {
719
        $key = $key ?: $this->getPk();
720
721
        if (is_null($sort)) {
722
            $order = $this->getOptions('order');
723
            if (!empty($order)) {
724
                $sort = $order[$key] ?? 'desc';
725
            } else {
726
                $this->order($key, 'desc');
727
                $sort = 'desc';
728
            }
729
        } else {
730
            $this->order($key, $sort);
731
        }
732
733
        $result = $this->when($lastId, function ($query) use ($key, $sort, $lastId) {
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
734
            $query->where($key, 'asc' == $sort ? '>' : '<', $lastId);
735
        })->limit($limit)->select();
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
736
737
        $last = $result->last();
738
739
        $result->first();
740
741
        return [
742
            'data'   => $result,
743
            'lastId' => $last[$key],
744
        ];
745
    }
746
747
    /**
748
     * 表达式方式指定当前操作的数据表
749
     * @access public
750
     * @param mixed $table 表名
751
     * @return $this
752
     */
753
    public function tableRaw(string $table)
754
    {
755
        $this->options['table'] = new Raw($table);
756
757
        return $this;
758
    }
759
760
    /**
761
     * 指定当前操作的数据表
762
     * @access public
763
     * @param mixed $table 表名
764
     * @return $this
765
     */
766
    public function table($table)
767
    {
768
        if (is_string($table)) {
769
            if (strpos($table, ')')) {
770
                // 子查询
771
            } elseif (false === strpos($table, ',')) {
772
                if (strpos($table, ' ')) {
773
                    list($item, $alias) = explode(' ', $table);
774
                    $table              = [];
775
                    $this->alias([$item => $alias]);
776
                    $table[$item] = $alias;
777
                }
778
            } else {
779
                $tables = explode(',', $table);
780
                $table  = [];
781
782
                foreach ($tables as $item) {
783
                    $item = trim($item);
784
                    if (strpos($item, ' ')) {
785
                        list($item, $alias) = explode(' ', $item);
786
                        $this->alias([$item => $alias]);
787
                        $table[$item] = $alias;
788
                    } else {
789
                        $table[] = $item;
790
                    }
791
                }
792
            }
793
        } elseif (is_array($table)) {
794
            $tables = $table;
795
            $table  = [];
796
797
            foreach ($tables as $key => $val) {
798
                if (is_numeric($key)) {
799
                    $table[] = $val;
800
                } else {
801
                    $this->alias([$key => $val]);
802
                    $table[$key] = $val;
803
                }
804
            }
805
        }
806
807
        $this->options['table'] = $table;
808
809
        return $this;
810
    }
811
812
    /**
813
     * USING支持 用于多表删除
814
     * @access public
815
     * @param mixed $using USING
816
     * @return $this
817
     */
818
    public function using($using)
819
    {
820
        $this->options['using'] = $using;
821
        return $this;
822
    }
823
824
    /**
825
     * 存储过程调用
826
     * @access public
827
     * @param bool $procedure 是否为存储过程查询
828
     * @return $this
829
     */
830
    public function procedure(bool $procedure = true)
831
    {
832
        $this->options['procedure'] = $procedure;
833
        return $this;
834
    }
835
836
    /**
837
     * 指定排序 order('id','desc') 或者 order(['id'=>'desc','create_time'=>'desc'])
838
     * @access public
839
     * @param string|array|Raw $field 排序字段
840
     * @param string           $order 排序
841
     * @return $this
842
     */
843
    public function order($field, string $order = '')
844
    {
845
        if (empty($field)) {
846
            return $this;
847
        } elseif ($field instanceof Raw) {
848
            $this->options['order'][] = $field;
849
            return $this;
850
        }
851
852
        if (is_string($field)) {
853
            if (!empty($this->options['via'])) {
854
                $field = $this->options['via'] . '.' . $field;
855
            }
856
            if (strpos($field, ',')) {
857
                $field = array_map('trim', explode(',', $field));
858
            } else {
859
                $field = empty($order) ? $field : [$field => $order];
860
            }
861
        } elseif (!empty($this->options['via'])) {
862
            foreach ($field as $key => $val) {
863
                if (is_numeric($key)) {
864
                    $field[$key] = $this->options['via'] . '.' . $val;
865
                } else {
866
                    $field[$this->options['via'] . '.' . $key] = $val;
867
                    unset($field[$key]);
868
                }
869
            }
870
        }
871
872
        if (!isset($this->options['order'])) {
873
            $this->options['order'] = [];
874
        }
875
876
        if (is_array($field)) {
877
            $this->options['order'] = array_merge($this->options['order'], $field);
878
        } else {
879
            $this->options['order'][] = $field;
880
        }
881
882
        return $this;
883
    }
884
885
    /**
886
     * 表达式方式指定Field排序
887
     * @access public
888
     * @param string $field 排序字段
889
     * @param array  $bind  参数绑定
890
     * @return $this
891
     */
892
    public function orderRaw(string $field, array $bind = [])
893
    {
894
        if (!empty($bind)) {
895
            $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

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

1188
            /** @scrutinizer ignore-call */ 
1189
            $this->pk = $this->connection->getPk($this->getTable());
Loading history...
1189
        }
1190
1191
        return $this->pk;
1192
    }
1193
1194
    /**
1195
     * 查询参数批量赋值
1196
     * @access protected
1197
     * @param array $options 表达式参数
1198
     * @return $this
1199
     */
1200
    protected function options(array $options)
1201
    {
1202
        $this->options = $options;
1203
        return $this;
1204
    }
1205
1206
    /**
1207
     * 获取当前的查询参数
1208
     * @access public
1209
     * @param string $name 参数名
1210
     * @return mixed
1211
     */
1212
    public function getOptions(string $name = '')
1213
    {
1214
        if ('' === $name) {
1215
            return $this->options;
1216
        }
1217
1218
        return $this->options[$name] ?? null;
1219
    }
1220
1221
    /**
1222
     * 设置当前的查询参数
1223
     * @access public
1224
     * @param string $option 参数名
1225
     * @param mixed  $value  参数值
1226
     * @return $this
1227
     */
1228
    public function setOption(string $option, $value)
1229
    {
1230
        $this->options[$option] = $value;
1231
        return $this;
1232
    }
1233
1234
    /**
1235
     * 设置当前字段添加的表别名
1236
     * @access public
1237
     * @param string $via 临时表别名
1238
     * @return $this
1239
     */
1240
    public function via(string $via = '')
1241
    {
1242
        $this->options['via'] = $via;
1243
1244
        return $this;
1245
    }
1246
1247
    /**
1248
     * 保存记录 自动判断insert或者update
1249
     * @access public
1250
     * @param array $data        数据
1251
     * @param bool  $forceInsert 是否强制insert
1252
     * @return integer
1253
     */
1254
    public function save(array $data = [], bool $forceInsert = false)
1255
    {
1256
        if ($forceInsert) {
1257
            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...
1258
        }
1259
1260
        $this->options['data'] = array_merge($this->options['data'] ?? [], $data);
1261
1262
        if (!empty($this->options['where'])) {
1263
            $isUpdate = true;
1264
        } else {
1265
            $isUpdate = $this->parseUpdateData($this->options['data']);
1266
        }
1267
1268
        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...
1269
    }
1270
1271
    /**
1272
     * 插入记录
1273
     * @access public
1274
     * @param array   $data         数据
1275
     * @param boolean $getLastInsID 返回自增主键
1276
     * @return integer|string
1277
     */
1278
    public function insert(array $data = [], bool $getLastInsID = false)
1279
    {
1280
        if (!empty($data)) {
1281
            $this->options['data'] = $data;
1282
        }
1283
1284
        return $this->connection->insert($this, $getLastInsID);
1285
    }
1286
1287
    /**
1288
     * 插入记录并获取自增ID
1289
     * @access public
1290
     * @param array $data 数据
1291
     * @return integer|string
1292
     */
1293
    public function insertGetId(array $data)
1294
    {
1295
        return $this->insert($data, true);
1296
    }
1297
1298
    /**
1299
     * 批量插入记录
1300
     * @access public
1301
     * @param array   $dataSet 数据集
1302
     * @param integer $limit   每次写入数据限制
1303
     * @return integer
1304
     */
1305
    public function insertAll(array $dataSet = [], int $limit = 0): int
1306
    {
1307
        if (empty($dataSet)) {
1308
            $dataSet = $this->options['data'] ?? [];
1309
        }
1310
1311
        if (empty($limit) && !empty($this->options['limit']) && is_numeric($this->options['limit'])) {
1312
            $limit = (int) $this->options['limit'];
1313
        }
1314
1315
        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

1315
        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...
1316
    }
1317
1318
    /**
1319
     * 通过Select方式插入记录
1320
     * @access public
1321
     * @param array  $fields 要插入的数据表字段名
1322
     * @param string $table  要插入的数据表名
1323
     * @return integer
1324
     * @throws PDOException
1325
     */
1326
    public function selectInsert(array $fields, string $table): int
1327
    {
1328
        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

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

1561
            $this->/** @scrutinizer ignore-call */ 
1562
                   parseView($options);
Loading history...
1562
        }
1563
1564
        if (!isset($options['field'])) {
1565
            $options['field'] = '*';
1566
        }
1567
1568
        foreach (['data', 'order', 'join', 'union'] as $name) {
1569
            if (!isset($options[$name])) {
1570
                $options[$name] = [];
1571
            }
1572
        }
1573
1574
        if (!isset($options['strict'])) {
1575
            $options['strict'] = $this->connection->getConfig('fields_strict');
1576
        }
1577
1578
        foreach (['master', 'lock', 'fetch_sql', 'array', 'distinct', 'procedure'] as $name) {
1579
            if (!isset($options[$name])) {
1580
                $options[$name] = false;
1581
            }
1582
        }
1583
1584
        foreach (['group', 'having', 'limit', 'force', 'comment', 'partition', 'duplicate', 'extra'] as $name) {
1585
            if (!isset($options[$name])) {
1586
                $options[$name] = '';
1587
            }
1588
        }
1589
1590
        if (isset($options['page'])) {
1591
            // 根据页数计算limit
1592
            list($page, $listRows) = $options['page'];
1593
            $page                  = $page > 0 ? $page : 1;
1594
            $listRows              = $listRows ?: (is_numeric($options['limit']) ? $options['limit'] : 20);
1595
            $offset                = $listRows * ($page - 1);
1596
            $options['limit']      = $offset . ',' . $listRows;
1597
        }
1598
1599
        $this->options = $options;
1600
1601
        return $options;
1602
    }
1603
1604
    /**
1605
     * 分析数据是否存在更新条件
1606
     * @access public
1607
     * @param array $data 数据
1608
     * @return bool
1609
     * @throws Exception
1610
     */
1611
    public function parseUpdateData(&$data): bool
1612
    {
1613
        $pk       = $this->getPk();
1614
        $isUpdate = false;
1615
        // 如果存在主键数据 则自动作为更新条件
1616
        if (is_string($pk) && isset($data[$pk])) {
1617
            $this->where($pk, '=', $data[$pk]);
1618
            $this->options['key'] = $data[$pk];
1619
            unset($data[$pk]);
1620
            $isUpdate = true;
1621
        } elseif (is_array($pk)) {
1622
            foreach ($pk as $field) {
1623
                if (isset($data[$field])) {
1624
                    $this->where($field, '=', $data[$field]);
1625
                    $isUpdate = true;
1626
                } else {
1627
                    // 如果缺少复合主键数据则不执行
1628
                    throw new Exception('miss complex primary data');
1629
                }
1630
                unset($data[$field]);
1631
            }
1632
        }
1633
1634
        return $isUpdate;
1635
    }
1636
1637
    /**
1638
     * 把主键值转换为查询条件 支持复合主键
1639
     * @access public
1640
     * @param array|string $data 主键数据
1641
     * @return void
1642
     * @throws Exception
1643
     */
1644
    public function parsePkWhere($data): void
1645
    {
1646
        $pk = $this->getPk();
1647
1648
        if (is_string($pk)) {
1649
            // 获取数据表
1650
            if (empty($this->options['table'])) {
1651
                $this->options['table'] = $this->getTable();
1652
            }
1653
1654
            $table = is_array($this->options['table']) ? key($this->options['table']) : $this->options['table'];
1655
1656
            if (!empty($this->options['alias'][$table])) {
1657
                $alias = $this->options['alias'][$table];
1658
            }
1659
1660
            $key = isset($alias) ? $alias . '.' . $pk : $pk;
1661
            // 根据主键查询
1662
            if (is_array($data)) {
1663
                $this->where($key, 'in', $data);
1664
            } else {
1665
                $this->where($key, '=', $data);
1666
                $this->options['key'] = $data;
1667
            }
1668
        }
1669
    }
1670
1671
    /**
1672
     * 获取模型的更新条件
1673
     * @access protected
1674
     * @param array $options 查询参数
1675
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
1676
    protected function getModelUpdateCondition(array $options)
1677
    {
1678
        return $options['where']['AND'] ?? null;
1679
    }
1680
}
1681