Completed
Push — 6.0 ( 41214e...845f81 )
by liu
06:11 queued 01:15
created

Query::data()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
1 ignored issue
show
Coding Style introduced by
You must use "/**" style comments for a file comment
Loading history...
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 Closure;
16
use PDO;
17
use PDOStatement;
18
use think\App;
19
use think\Collection;
20
use think\Db;
21
use think\db\exception\BindParamException;
22
use think\db\exception\DataNotFoundException;
23
use think\db\exception\ModelNotFoundException;
24
use think\Exception;
25
use think\exception\DbException;
26
use think\exception\PDOException;
27
use think\Model;
28
use think\model\Collection as ModelCollection;
29
use think\model\Relation;
30
use think\model\relation\OneToOne;
31
use think\Paginator;
32
33
/**
34
 * 数据查询类
35
 */
5 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @package tag in class comment
Loading history...
Coding Style introduced by
Missing @author tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
36
class Query
37
{
38
    /**
39
     * 当前数据库连接对象
40
     * @var Connection
41
     */
42
    protected $connection;
43
44
    /**
45
     * 当前模型对象
46
     * @var Model
47
     */
48
    protected $model;
49
50
    /**
51
     * Db对象
52
     * @var Db
53
     */
54
    protected $db;
55
56
    /**
57
     * 当前数据表名称(不含前缀)
58
     * @var string
59
     */
60
    protected $name = '';
61
62
    /**
63
     * 当前数据表主键
64
     * @var string|array
65
     */
66
    protected $pk;
67
68
    /**
69
     * 当前数据表前缀
70
     * @var string
71
     */
72
    protected $prefix = '';
73
74
    /**
75
     * 当前查询参数
76
     * @var array
77
     */
78
    protected $options = [];
79
80
    /**
81
     * 当前参数绑定
82
     * @var array
83
     */
84
    protected $bind = [];
85
86
    /**
87
     * 日期查询表达式
88
     * @var array
89
     */
90
    protected $timeRule = [
91
        'today'      => ['today', 'tomorrow'],
92
        'yesterday'  => ['yesterday', 'today'],
93
        'week'       => ['this week 00:00:00', 'next week 00:00:00'],
94
        'last week'  => ['last week 00:00:00', 'this week 00:00:00'],
95
        'month'      => ['first Day of this month 00:00:00', 'first Day of next month 00:00:00'],
96
        'last month' => ['first Day of last month 00:00:00', 'first Day of this month 00:00:00'],
97
        'year'       => ['this year 1/1', 'next year 1/1'],
98
        'last year'  => ['last year 1/1', 'this year 1/1'],
99
    ];
100
101
    /**
102
     * 架构函数
103
     * @access public
104
     * @param Connection $connection 数据库连接对象
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
105
     */
106
    public function __construct(Connection $connection)
107
    {
108
        $this->connection = $connection;
109
110
        $this->prefix = $this->connection->getConfig('prefix');
111
    }
112
113
    /**
114
     * 创建一个新的查询对象
115
     * @access public
116
     * @return Query
117
     */
118
    public function newQuery()
119
    {
120
        $query = new static($this->connection);
121
122
        if ($this->model) {
123
            $query->model($this->model);
124
        }
125
126
        if (isset($this->options['table'])) {
127
            $query->table($this->options['table']);
128
        } else {
129
            $query->name($this->name);
130
        }
131
132
        $query->setDb($this->db);
133
134
        return $query;
135
    }
136
137
    /**
138
     * 利用__call方法实现一些特殊的Model方法
139
     * @access public
140
     * @param string $method 方法名称
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
141
     * @param array  $args   调用参数
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
142
     * @return mixed
143
     * @throws DbException
144
     * @throws Exception
145
     */
146
    public function __call(string $method, array $args)
147
    {
148
        if (strtolower(substr($method, 0, 5)) == 'getby') {
149
            // 根据某个字段获取记录
150
            $field = App::parseName(substr($method, 5));
151
            return $this->where($field, '=', $args[0])->find();
152
        } elseif (strtolower(substr($method, 0, 10)) == 'getfieldby') {
153
            // 根据某个字段获取记录的某个值
154
            $name = App::parseName(substr($method, 10));
155
            return $this->where($name, '=', $args[0])->value($args[1]);
156
        } elseif (strtolower(substr($method, 0, 7)) == 'whereor') {
157
            $name = App::parseName(substr($method, 7));
158
            array_unshift($args, $name);
159
            return call_user_func_array([$this, 'whereOr'], $args);
160
        } elseif (strtolower(substr($method, 0, 5)) == 'where') {
161
            $name = App::parseName(substr($method, 5));
162
            array_unshift($args, $name);
163
            return call_user_func_array([$this, 'where'], $args);
164
        } elseif ($this->model && method_exists($this->model, 'scope' . $method)) {
165
            // 动态调用命名范围
166
            $method = 'scope' . $method;
167
            array_unshift($args, $this);
168
169
            call_user_func_array([$this->model, $method], $args);
170
            return $this;
171
        } else {
172
            throw new Exception('method not exist:' . static::class . '->' . $method);
173
        }
174
    }
175
176
    /**
177
     * 获取当前的数据库Connection对象
178
     * @access public
179
     * @return Connection
180
     */
181
    public function getConnection()
182
    {
183
        return $this->connection;
184
    }
185
186
    /**
187
     * 设置当前的数据库Connection对象
188
     * @access public
189
     * @param Connection $connection 数据库连接对象
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
190
     * @return $this
191
     */
192
    public function setConnection($connection)
193
    {
194
        $this->connection = $connection;
195
196
        return $this;
197
    }
198
199
    /**
200
     * 设置Db对象
201
     * @access public
202
     * @param Db $db
1 ignored issue
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
203
     * @return $this
204
     */
205
    public function setDb(Db $db)
206
    {
207
        $this->db = $db;
208
        $this->connection->setDb($db);
209
        return $this;
210
    }
211
212
    /**
213
     * 获取Db对象
214
     * @access public
215
     * @return Db
216
     */
217
    public function getDb()
218
    {
219
        return $this->db;
220
    }
221
222
    /**
223
     * 指定模型
224
     * @access public
225
     * @param Model $model 模型对象实例
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
226
     * @return $this
227
     */
228
    public function model(Model $model)
229
    {
230
        $this->model = $model;
231
        return $this;
232
    }
233
234
    /**
235
     * 获取当前的模型对象
236
     * @access public
237
     * @param bool $clear 是否需要清空查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
238
     * @return Model|null
239
     */
240
    public function getModel(bool $clear = true)
241
    {
242
        return $this->model ? $this->model->setQuery($this, $clear) : null;
243
    }
244
245
    /**
246
     * 指定当前数据表名(不含前缀)
247
     * @access public
248
     * @param string $name 不含前缀的数据表名字
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
249
     * @return $this
250
     */
251
    public function name(string $name)
252
    {
253
        $this->name = $name;
254
        return $this;
255
    }
256
257
    /**
258
     * 获取当前的数据表名称
259
     * @access public
260
     * @return string
261
     */
262
    public function getName(): string
263
    {
264
        return $this->name ?: $this->model->getName();
265
    }
266
267
    /**
268
     * 获取数据库的配置参数
269
     * @access public
270
     * @param string $name 参数名称
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
271
     * @return mixed
272
     */
273
    public function getConfig(string $name = '')
274
    {
275
        return $this->connection->getConfig($name);
276
    }
277
278
    /**
279
     * 得到当前或者指定名称的数据表
280
     * @access public
281
     * @param string $name 不含前缀的数据表名字
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
282
     * @return mixed
283
     */
284
    public function getTable(string $name = '')
285
    {
286
        if (empty($name) && isset($this->options['table'])) {
287
            return $this->options['table'];
288
        }
289
290
        $name = $name ?: $this->name;
291
292
        return $this->prefix . App::parseName($name);
293
    }
294
295
    /**
296
     * 获取数据表字段信息
297
     * @access public
298
     * @param string $tableName 数据表名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
299
     * @return array
300
     */
301
    public function getTableFields($tableName = ''): array
302
    {
303
        if ('' == $tableName) {
304
            $tableName = $this->getTable();
305
        }
306
307
        return $this->connection->getTableFields($tableName);
308
    }
309
310
    /**
311
     * 设置字段类型信息
312
     * @access public
313
     * @param array $type 字段类型信息
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
314
     * @return $this
315
     */
316
    public function setFieldType(array $type)
317
    {
318
        $this->options['field_type'] = $type;
319
        return $this;
320
    }
321
322
    /**
323
     * 获取详细字段类型信息
324
     * @access public
325
     * @param string $tableName 数据表名称
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
326
     * @return array
327
     */
328
    public function getFields(string $tableName = ''): array
329
    {
330
        return $this->connection->getFields($tableName ?: $this->getTable());
331
    }
332
333
    /**
334
     * 获取字段类型信息
335
     * @access public
336
     * @return array
337
     */
338
    public function getFieldsType(): array
339
    {
340
        if (!empty($this->options['field_type'])) {
341
            return $this->options['field_type'];
342
        }
343
344
        return $this->connection->getFieldsType($this->getTable());
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->connection...Type($this->getTable()) could return the type string which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
345
    }
346
347
    /**
348
     * 获取字段类型信息
349
     * @access public
350
     * @param string $field 字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
351
     * @return string|null
352
     */
353
    public function getFieldType(string $field)
354
    {
355
        $fieldType = $this->getFieldsType();
356
357
        return $fieldType[$field] ?? null;
358
    }
359
360
    /**
361
     * 获取字段类型信息
362
     * @access public
363
     * @return array
364
     */
365
    public function getFieldsBindType(): array
366
    {
367
        $fieldType = $this->getFieldsType();
368
369
        return array_map([$this->connection, 'getFieldBindType'], $fieldType);
370
    }
371
372
    /**
373
     * 获取字段类型信息
374
     * @access public
375
     * @param string $field 字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
376
     * @return int
377
     */
378
    public function getFieldBindType(string $field): int
379
    {
380
        $fieldType = $this->getFieldType($field);
381
382
        return $this->connection->getFieldBindType($fieldType ?: '');
383
    }
384
385
    /**
386
     * 执行查询 返回数据集
387
     * @access public
388
     * @param string $sql  sql指令
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
389
     * @param array  $bind 参数绑定
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
390
     * @return array
391
     * @throws BindParamException
392
     * @throws PDOException
393
     */
394
    public function query(string $sql, array $bind = []): array
395
    {
396
        return $this->connection->query($this, $sql, $bind, true);
397
    }
398
399
    /**
400
     * 执行语句
401
     * @access public
402
     * @param string $sql  sql指令
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
403
     * @param array  $bind 参数绑定
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
404
     * @return int
405
     * @throws BindParamException
406
     * @throws PDOException
407
     */
408
    public function execute(string $sql, array $bind = []): int
409
    {
410
        return $this->connection->execute($this, $sql, $bind, true);
411
    }
412
413
    /**
414
     * 获取最近插入的ID
415
     * @access public
416
     * @param string $sequence 自增序列名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
417
     * @return mixed
418
     */
419
    public function getLastInsID(string $sequence = null)
420
    {
421
        $insertId = $this->connection->getLastInsID($sequence);
422
423
        $pk = $this->getPk();
424
425
        if (is_string($pk)) {
426
            $type = $this->getFieldBindType($pk);
427
428
            if (PDO::PARAM_INT == $type) {
429
                $insertId = (int) $insertId;
430
            } elseif (Connection::PARAM_FLOAT == $type) {
431
                $insertId = (float) $insertId;
432
            }
433
        }
434
435
        return $insertId;
436
    }
437
438
    /**
439
     * 获取返回或者影响的记录数
440
     * @access public
441
     * @return integer
442
     */
443
    public function getNumRows(): int
444
    {
445
        return $this->connection->getNumRows();
446
    }
447
448
    /**
449
     * 获取最近一次查询的sql语句
450
     * @access public
451
     * @return string
452
     */
453
    public function getLastSql(): string
454
    {
455
        return $this->connection->getLastSql();
456
    }
457
458
    /**
459
     * 执行数据库事务
460
     * @access public
461
     * @param callable $callback 数据操作方法回调
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
462
     * @return mixed
463
     */
464
    public function transaction(callable $callback)
465
    {
466
        return $this->connection->transaction($callback);
467
    }
468
469
    /**
470
     * 启动事务
471
     * @access public
472
     * @return void
473
     */
474
    public function startTrans(): void
475
    {
476
        $this->connection->startTrans();
477
    }
478
479
    /**
480
     * 用于非自动提交状态下面的查询提交
481
     * @access public
482
     * @return void
483
     * @throws PDOException
484
     */
485
    public function commit(): void
486
    {
487
        $this->connection->commit();
488
    }
489
490
    /**
491
     * 事务回滚
492
     * @access public
493
     * @return void
494
     * @throws PDOException
495
     */
496
    public function rollback(): void
497
    {
498
        $this->connection->rollback();
499
    }
500
501
    /**
502
     * 批处理执行SQL语句
503
     * 批处理的指令都认为是execute操作
504
     * @access public
505
     * @param array $sql SQL批处理指令
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
506
     * @return bool
507
     */
508
    public function batchQuery(array $sql = []): bool
509
    {
510
        return $this->connection->batchQuery($this, $sql);
511
    }
512
513
    /**
514
     * 得到某个字段的值
515
     * @access public
516
     * @param string $field   字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
517
     * @param mixed  $default 默认值
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
518
     * @return mixed
519
     */
520
    public function value(string $field, $default = null)
521
    {
522
        return $this->connection->value($this, $field, $default);
523
    }
524
525
    /**
526
     * 得到某个列的数组
527
     * @access public
528
     * @param string $field 字段名 多个字段用逗号分隔
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
529
     * @param string $key   索引
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
530
     * @return array
531
     */
532
    public function column(string $field, string $key = ''): array
533
    {
534
        return $this->connection->column($this, $field, $key);
535
    }
536
537
    /**
538
     * 聚合查询
539
     * @access protected
540
     * @param string     $aggregate 聚合方法
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
541
     * @param string|Raw $field     字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
542
     * @param bool       $force     强制转为数字类型
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
543
     * @return mixed
544
     */
545
    protected function aggregate(string $aggregate, $field, bool $force = false)
546
    {
547
        return $this->connection->aggregate($this, $aggregate, $field, $force);
548
    }
549
550
    /**
551
     * COUNT查询
552
     * @access public
553
     * @param string|Raw $field 字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
554
     * @return int
555
     */
556
    public function count(string $field = '*'): int
557
    {
558
        if (!empty($this->options['group'])) {
559
            // 支持GROUP
560
            $options = $this->getOptions();
561
            $subSql  = $this->options($options)->field('count(' . $field . ') AS think_count')->bind($this->bind)->buildSql();
562
563
            $query = $this->newQuery()->table([$subSql => '_group_count_']);
564
565
            $count = $query->aggregate('COUNT', '*');
566
        } else {
567
            $count = $this->aggregate('COUNT', $field);
568
        }
569
570
        return (int) $count;
571
    }
572
573
    /**
574
     * SUM查询
575
     * @access public
576
     * @param string|Raw $field 字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
577
     * @return float
578
     */
579
    public function sum($field): float
580
    {
581
        return $this->aggregate('SUM', $field, true);
582
    }
583
584
    /**
585
     * MIN查询
586
     * @access public
587
     * @param string|Raw $field 字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
588
     * @param bool       $force 强制转为数字类型
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
589
     * @return mixed
590
     */
591
    public function min($field, bool $force = true)
592
    {
593
        return $this->aggregate('MIN', $field, $force);
594
    }
595
596
    /**
597
     * MAX查询
598
     * @access public
599
     * @param string|Raw $field 字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
600
     * @param bool       $force 强制转为数字类型
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
601
     * @return mixed
602
     */
603
    public function max($field, bool $force = true)
604
    {
605
        return $this->aggregate('MAX', $field, $force);
606
    }
607
608
    /**
609
     * AVG查询
610
     * @access public
611
     * @param string|Raw $field 字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
612
     * @return float
613
     */
614
    public function avg($field): float
615
    {
616
        return $this->aggregate('AVG', $field, true);
617
    }
618
619
    /**
620
     * 查询SQL组装 join
621
     * @access public
622
     * @param mixed  $join      关联的表名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
623
     * @param mixed  $condition 条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
624
     * @param string $type      JOIN类型
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
625
     * @param array  $bind      参数绑定
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
626
     * @return $this
627
     */
628
    public function join($join, string $condition = null, string $type = 'INNER', array $bind = [])
629
    {
630
        $table = $this->getJoinTable($join);
631
632
        if (!empty($bind) && $condition) {
633
            $this->bindParams($condition, $bind);
634
        }
635
636
        $this->options['join'][] = [$table, strtoupper($type), $condition];
637
638
        return $this;
639
    }
640
641
    /**
642
     * LEFT JOIN
643
     * @access public
644
     * @param mixed $join      关联的表名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
645
     * @param mixed $condition 条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
646
     * @param array $bind      参数绑定
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
647
     * @return $this
648
     */
649
    public function leftJoin($join, string $condition = null, array $bind = [])
650
    {
651
        return $this->join($join, $condition, 'LEFT', $bind);
652
    }
653
654
    /**
655
     * RIGHT JOIN
656
     * @access public
657
     * @param mixed $join      关联的表名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
658
     * @param mixed $condition 条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
659
     * @param array $bind      参数绑定
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
660
     * @return $this
661
     */
662
    public function rightJoin($join, string $condition = null, array $bind = [])
663
    {
664
        return $this->join($join, $condition, 'RIGHT', $bind);
665
    }
666
667
    /**
668
     * FULL JOIN
669
     * @access public
670
     * @param mixed $join      关联的表名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
671
     * @param mixed $condition 条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
672
     * @param array $bind      参数绑定
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
673
     * @return $this
674
     */
675
    public function fullJoin($join, string $condition = null, array $bind = [])
676
    {
677
        return $this->join($join, $condition, 'FULL');
678
    }
679
680
    /**
681
     * 获取Join表名及别名 支持
682
     * ['prefix_table或者子查询'=>'alias'] 'table alias'
683
     * @access protected
684
     * @param array|string|Raw $join  JION表名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
685
     * @param string           $alias 别名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
686
     * @return string|array
687
     */
688
    protected function getJoinTable($join, &$alias = null)
689
    {
690
        if (is_array($join)) {
691
            $table = $join;
692
            $alias = array_shift($join);
693
            return $table;
694
        } elseif ($join instanceof Raw) {
695
            return $join;
696
        }
697
698
        $join = trim($join);
699
700
        if (false !== strpos($join, '(')) {
701
            // 使用子查询
702
            $table = $join;
703
        } else {
704
            // 使用别名
705
            if (strpos($join, ' ')) {
706
                // 使用别名
707
                list($table, $alias) = explode(' ', $join);
708
            } else {
709
                $table = $join;
710
                if (false === strpos($join, '.')) {
711
                    $alias = $join;
712
                }
713
            }
714
715
            if ($this->prefix && false === strpos($table, '.') && 0 !== strpos($table, $this->prefix)) {
716
                $table = $this->getTable($table);
717
            }
718
        }
719
720
        if (!empty($alias) && $table != $alias) {
721
            $table = [$table => $alias];
722
        }
723
724
        return $table;
725
    }
726
727
    /**
728
     * 查询SQL组装 union
729
     * @access public
730
     * @param mixed   $union UNION
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
731
     * @param boolean $all   是否适用UNION ALL
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
732
     * @return $this
733
     */
734
    public function union($union, bool $all = false)
735
    {
736
        $this->options['union']['type'] = $all ? 'UNION ALL' : 'UNION';
737
738
        if (is_array($union)) {
739
            $this->options['union'] = array_merge($this->options['union'], $union);
740
        } else {
741
            $this->options['union'][] = $union;
742
        }
743
744
        return $this;
745
    }
746
747
    /**
748
     * 查询SQL组装 union all
749
     * @access public
750
     * @param mixed $union UNION数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
751
     * @return $this
752
     */
753
    public function unionAll($union)
754
    {
755
        return $this->union($union, true);
756
    }
757
758
    /**
759
     * 指定查询字段
760
     * @access public
761
     * @param mixed $field 字段信息
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
762
     * @return $this
763
     */
764
    public function field($field)
765
    {
766
        if (empty($field)) {
767
            return $this;
768
        } elseif ($field instanceof Raw) {
769
            $this->options['field'][] = $field;
770
            return $this;
771
        }
772
773
        if (is_string($field)) {
774
            if (preg_match('/[\<\'\"\(]/', $field)) {
775
                return $this->fieldRaw($field);
776
            }
777
778
            $field = array_map('trim', explode(',', $field));
779
        }
780
781
        if (true === $field) {
782
            // 获取全部字段
783
            $fields = $this->getTableFields();
784
            $field  = $fields ?: ['*'];
0 ignored issues
show
introduced by
$fields is an empty array, thus is always false.
Loading history...
785
        }
786
787
        if (isset($this->options['field'])) {
788
            $field = array_merge((array) $this->options['field'], $field);
789
        }
790
791
        $this->options['field'] = array_unique($field);
792
793
        return $this;
794
    }
795
796
    /**
797
     * 指定要排除的查询字段
798
     * @access public
799
     * @param array|string $field 要排除的字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
800
     * @return $this
801
     */
802
    public function withoutField($field)
803
    {
804
        if (empty($field)) {
805
            return $this;
806
        }
807
808
        if (is_string($field)) {
809
            $field = array_map('trim', explode(',', $field));
810
        }
811
812
        // 字段排除
813
        $fields = $this->getTableFields();
814
        $field  = $fields ? array_diff($fields, $field) : $field;
0 ignored issues
show
introduced by
$fields is an empty array, thus is always false.
Loading history...
815
816
        if (isset($this->options['field'])) {
817
            $field = array_merge((array) $this->options['field'], $field);
818
        }
819
820
        $this->options['field'] = array_unique($field);
821
822
        return $this;
823
    }
824
825
    /**
826
     * 指定其它数据表的查询字段
827
     * @access public
828
     * @param mixed   $field     字段信息
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
829
     * @param string  $tableName 数据表名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
830
     * @param string  $prefix    字段前缀
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
831
     * @param string  $alias     别名前缀
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
832
     * @return $this
833
     */
834
    public function tableField($field, string $tableName, string $prefix = '', string $alias = '')
835
    {
836
        if (empty($field)) {
837
            return $this;
838
        }
839
840
        if (is_string($field)) {
841
            $field = array_map('trim', explode(',', $field));
842
        }
843
844
        if (true === $field) {
845
            // 获取全部字段
846
            $fields = $this->getTableFields($tableName);
847
            $field  = $fields ?: ['*'];
0 ignored issues
show
introduced by
$fields is an empty array, thus is always false.
Loading history...
848
        }
849
850
        // 添加统一的前缀
851
        $prefix = $prefix ?: $tableName;
852
        foreach ($field as $key => &$val) {
853
            if (is_numeric($key) && $alias) {
854
                $field[$prefix . '.' . $val] = $alias . $val;
855
                unset($field[$key]);
856
            } elseif (is_numeric($key)) {
857
                $val = $prefix . '.' . $val;
858
            }
859
        }
860
861
        if (isset($this->options['field'])) {
862
            $field = array_merge((array) $this->options['field'], $field);
863
        }
864
865
        $this->options['field'] = array_unique($field);
866
867
        return $this;
868
    }
869
870
    /**
871
     * 表达式方式指定查询字段
872
     * @access public
873
     * @param string $field 字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
874
     * @return $this
875
     */
876
    public function fieldRaw(string $field)
877
    {
878
        $this->options['field'][] = new Raw($field);
879
880
        return $this;
881
    }
882
883
    /**
884
     * 设置数据
885
     * @access public
886
     * @param array $data 数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
887
     * @return $this
888
     */
889
    public function data(array $data)
890
    {
891
        $this->options['data'] = $data;
892
893
        return $this;
894
    }
895
896
    /**
897
     * 字段值增长
898
     * @access public
899
     * @param string  $field    字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
900
     * @param float   $step     增长值
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
901
     * @param integer $lazyTime 延时时间(s)
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
902
     * @param string  $op       INC/DEC
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
903
     * @return $this
904
     */
905
    public function inc(string $field, float $step = 1, int $lazyTime = 0, string $op = 'INC')
906
    {
907
        if ($lazyTime > 0) {
908
            // 延迟写入
909
            $condition = $this->options['where'] ?? [];
910
911
            $guid = md5($this->getTable() . '_' . $field . '_' . serialize($condition));
912
            $step = $this->connection->lazyWrite($op, $guid, $step, $lazyTime);
913
914
            if (false === $step) {
915
                return $this;
916
            }
917
918
            $op = 'INC';
919
        }
920
921
        $this->options['data'][$field] = [$op, $step];
922
923
        return $this;
924
    }
925
926
    /**
927
     * 字段值减少
928
     * @access public
929
     * @param string  $field    字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
930
     * @param float   $step     增长值
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
931
     * @param integer $lazyTime 延时时间(s)
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
932
     * @return $this
933
     */
934
    public function dec(string $field, float $step = 1, int $lazyTime = 0)
935
    {
936
        return $this->inc($field, $step, $lazyTime, 'DEC');
937
    }
938
939
    /**
940
     * 使用表达式设置数据
941
     * @access public
942
     * @param string $field 字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
943
     * @param string $value 字段值
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
944
     * @return $this
945
     */
946
    public function exp(string $field, string $value)
947
    {
948
        $this->options['data'][$field] = new Raw($value);
949
        return $this;
950
    }
951
952
    /**
953
     * 指定JOIN查询字段
954
     * @access public
955
     * @param string|array $join  数据表
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
956
     * @param string|array $field 查询字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
957
     * @param string       $on    JOIN条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
958
     * @param string       $type  JOIN类型
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
959
     * @param array        $bind  参数绑定
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
960
     * @return $this
961
     */
962
    public function view($join, $field = true, $on = null, string $type = 'INNER', array $bind = [])
963
    {
964
        $this->options['view'] = true;
965
966
        $fields = [];
967
        $table  = $this->getJoinTable($join, $alias);
968
969
        if (true === $field) {
970
            $fields = $alias . '.*';
971
        } else {
972
            if (is_string($field)) {
973
                $field = explode(',', $field);
974
            }
975
976
            foreach ($field as $key => $val) {
977
                if (is_numeric($key)) {
978
                    $fields[] = $alias . '.' . $val;
979
980
                    $this->options['map'][$val] = $alias . '.' . $val;
981
                } else {
982
                    if (preg_match('/[,=\.\'\"\(\s]/', $key)) {
983
                        $name = $key;
984
                    } else {
985
                        $name = $alias . '.' . $key;
986
                    }
987
988
                    $fields[] = $name . ' AS ' . $val;
989
990
                    $this->options['map'][$val] = $name;
991
                }
992
            }
993
        }
994
995
        $this->field($fields);
996
997
        if ($on) {
998
            $this->join($table, $on, $type, $bind);
999
        } else {
1000
            $this->table($table);
1001
        }
1002
1003
        return $this;
1004
    }
1005
1006
    /**
1007
     * 指定AND查询条件
1008
     * @access public
1009
     * @param mixed $field     查询字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1010
     * @param mixed $op        查询表达式
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1011
     * @param mixed $condition 查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1012
     * @return $this
1013
     */
1014
    public function where($field, $op = null, $condition = null)
1015
    {
1016
        if ($field instanceof $this) {
1017
            $this->parseQueryWhere($field);
1018
            return $this;
1019
        }
1020
1021
        $param = func_get_args();
1022
        array_shift($param);
1023
        return $this->parseWhereExp('AND', $field, $op, $condition, $param);
1024
    }
1025
1026
    /**
1027
     * 解析Query对象查询条件
1028
     * @access public
1029
     * @param Query $query 查询对象
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1030
     * @return void
1031
     */
1032
    protected function parseQueryWhere(Query $query): void
1033
    {
1034
        $this->options['where'] = $query->getOptions('where');
1035
1036
        if ($query->getOptions('via')) {
1037
            $via = $query->getOptions('via');
1038
            foreach ($this->options['where'] as $logic => &$where) {
1039
                foreach ($where as $key => &$val) {
1040
                    if (is_array($val) && !strpos($val[0], '.')) {
1041
                        $val[0] = $via . '.' . $val[0];
1042
                    }
1043
                }
1044
            }
1045
        }
1046
1047
        $this->bind($query->getBind(false));
1048
    }
1049
1050
    /**
1051
     * 指定OR查询条件
1052
     * @access public
1053
     * @param mixed $field     查询字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1054
     * @param mixed $op        查询表达式
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1055
     * @param mixed $condition 查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1056
     * @return $this
1057
     */
1058
    public function whereOr($field, $op = null, $condition = null)
1059
    {
1060
        $param = func_get_args();
1061
        array_shift($param);
1062
        return $this->parseWhereExp('OR', $field, $op, $condition, $param);
1063
    }
1064
1065
    /**
1066
     * 指定XOR查询条件
1067
     * @access public
1068
     * @param mixed $field     查询字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1069
     * @param mixed $op        查询表达式
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1070
     * @param mixed $condition 查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1071
     * @return $this
1072
     */
1073
    public function whereXor($field, $op = null, $condition = null)
1074
    {
1075
        $param = func_get_args();
1076
        array_shift($param);
1077
        return $this->parseWhereExp('XOR', $field, $op, $condition, $param);
1078
    }
1079
1080
    /**
1081
     * 指定Null查询条件
1082
     * @access public
1083
     * @param mixed  $field 查询字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1084
     * @param string $logic 查询逻辑 and or xor
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1085
     * @return $this
1086
     */
1087
    public function whereNull(string $field, string $logic = 'AND')
1088
    {
1089
        return $this->parseWhereExp($logic, $field, 'NULL', null, [], true);
1090
    }
1091
1092
    /**
1093
     * 指定NotNull查询条件
1094
     * @access public
1095
     * @param mixed  $field 查询字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1096
     * @param string $logic 查询逻辑 and or xor
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1097
     * @return $this
1098
     */
1099
    public function whereNotNull(string $field, string $logic = 'AND')
1100
    {
1101
        return $this->parseWhereExp($logic, $field, 'NOTNULL', null, [], true);
1102
    }
1103
1104
    /**
1105
     * 指定Exists查询条件
1106
     * @access public
1107
     * @param mixed  $condition 查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1108
     * @param string $logic     查询逻辑 and or xor
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1109
     * @return $this
1110
     */
1111
    public function whereExists($condition, string $logic = 'AND')
1112
    {
1113
        if (is_string($condition)) {
1114
            $condition = new Raw($condition);
1115
        }
1116
1117
        $this->options['where'][strtoupper($logic)][] = ['', 'EXISTS', $condition];
1118
        return $this;
1119
    }
1120
1121
    /**
1122
     * 指定NotExists查询条件
1123
     * @access public
1124
     * @param mixed  $condition 查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1125
     * @param string $logic     查询逻辑 and or xor
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1126
     * @return $this
1127
     */
1128
    public function whereNotExists($condition, string $logic = 'AND')
1129
    {
1130
        if (is_string($condition)) {
1131
            $condition = new Raw($condition);
1132
        }
1133
1134
        $this->options['where'][strtoupper($logic)][] = ['', 'NOT EXISTS', $condition];
1135
        return $this;
1136
    }
1137
1138
    /**
1139
     * 指定In查询条件
1140
     * @access public
1141
     * @param mixed  $field     查询字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1142
     * @param mixed  $condition 查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1143
     * @param string $logic     查询逻辑 and or xor
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1144
     * @return $this
1145
     */
1146
    public function whereIn(string $field, $condition, string $logic = 'AND')
1147
    {
1148
        return $this->parseWhereExp($logic, $field, 'IN', $condition, [], true);
1149
    }
1150
1151
    /**
1152
     * 指定NotIn查询条件
1153
     * @access public
1154
     * @param mixed  $field     查询字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1155
     * @param mixed  $condition 查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1156
     * @param string $logic     查询逻辑 and or xor
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1157
     * @return $this
1158
     */
1159
    public function whereNotIn(string $field, $condition, string $logic = 'AND')
1160
    {
1161
        return $this->parseWhereExp($logic, $field, 'NOT IN', $condition, [], true);
1162
    }
1163
1164
    /**
1165
     * 指定Like查询条件
1166
     * @access public
1167
     * @param mixed  $field     查询字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1168
     * @param mixed  $condition 查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1169
     * @param string $logic     查询逻辑 and or xor
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1170
     * @return $this
1171
     */
1172
    public function whereLike(string $field, $condition, string $logic = 'AND')
1173
    {
1174
        return $this->parseWhereExp($logic, $field, 'LIKE', $condition, [], true);
1175
    }
1176
1177
    /**
1178
     * 指定NotLike查询条件
1179
     * @access public
1180
     * @param mixed  $field     查询字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1181
     * @param mixed  $condition 查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1182
     * @param string $logic     查询逻辑 and or xor
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1183
     * @return $this
1184
     */
1185
    public function whereNotLike(string $field, $condition, string $logic = 'AND')
1186
    {
1187
        return $this->parseWhereExp($logic, $field, 'NOT LIKE', $condition, [], true);
1188
    }
1189
1190
    /**
1191
     * 指定Between查询条件
1192
     * @access public
1193
     * @param mixed  $field     查询字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1194
     * @param mixed  $condition 查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1195
     * @param string $logic     查询逻辑 and or xor
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1196
     * @return $this
1197
     */
1198
    public function whereBetween(string $field, $condition, string $logic = 'AND')
1199
    {
1200
        return $this->parseWhereExp($logic, $field, 'BETWEEN', $condition, [], true);
1201
    }
1202
1203
    /**
1204
     * 指定NotBetween查询条件
1205
     * @access public
1206
     * @param mixed  $field     查询字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1207
     * @param mixed  $condition 查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1208
     * @param string $logic     查询逻辑 and or xor
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1209
     * @return $this
1210
     */
1211
    public function whereNotBetween(string $field, $condition, string $logic = 'AND')
1212
    {
1213
        return $this->parseWhereExp($logic, $field, 'NOT BETWEEN', $condition, [], true);
1214
    }
1215
1216
    /**
1217
     * 指定FIND_IN_SET查询条件
1218
     * @access public
1219
     * @param mixed  $field     查询字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1220
     * @param mixed  $condition 查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1221
     * @param string $logic     查询逻辑 and or xor
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1222
     * @return $this
1223
     */
1224
    public function whereFindInSet(string $field, $condition, string $logic = 'AND')
1225
    {
1226
        return $this->parseWhereExp($logic, $field, 'FIND IN SET', $condition, [], true);
1227
    }
1228
1229
    /**
1230
     * 比较两个字段
1231
     * @access public
1232
     * @param string $field1   查询字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1233
     * @param string $operator 比较操作符
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1234
     * @param string $field2   比较字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1235
     * @param string $logic    查询逻辑 and or xor
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1236
     * @return $this
1237
     */
1238
    public function whereColumn(string $field1, string $operator, string $field2 = null, string $logic = 'AND')
1239
    {
1240
        if (is_null($field2)) {
1241
            $field2   = $operator;
1242
            $operator = '=';
1243
        }
1244
1245
        return $this->parseWhereExp($logic, $field1, 'COLUMN', [$operator, $field2], [], true);
1246
    }
1247
1248
    /**
1249
     * 设置软删除字段及条件
1250
     * @access public
1251
     * @param string $field     查询字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1252
     * @param mixed  $condition 查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1253
     * @return $this
1254
     */
1255
    public function useSoftDelete(string $field, $condition = null)
1256
    {
1257
        if ($field) {
1258
            $this->options['soft_delete'] = [$field, $condition];
1259
        }
1260
1261
        return $this;
1262
    }
1263
1264
    /**
1265
     * 指定Exp查询条件
1266
     * @access public
1267
     * @param mixed  $field 查询字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1268
     * @param string $where 查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1269
     * @param array  $bind  参数绑定
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1270
     * @param string $logic 查询逻辑 and or xor
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1271
     * @return $this
1272
     */
1273
    public function whereExp(string $field, string $where, array $bind = [], string $logic = 'AND')
1274
    {
1275
        if (!empty($bind)) {
1276
            $this->bindParams($where, $bind);
1277
        }
1278
1279
        $this->options['where'][$logic][] = [$field, 'EXP', new Raw($where)];
1280
1281
        return $this;
1282
    }
1283
1284
    /**
1285
     * 指定字段Raw查询
1286
     * @access public
1287
     * @param string $field     查询字段表达式
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1288
     * @param mixed  $op        查询表达式
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1289
     * @param string $condition 查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1290
     * @param string $logic     查询逻辑 and or xor
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1291
     * @return $this
1292
     */
1293
    public function whereFieldRaw(string $field, $op, $condition = null, string $logic = 'AND')
1294
    {
1295
        if (is_null($condition)) {
1296
            $condition = $op;
1297
            $op        = '=';
1298
        }
1299
1300
        $this->options['where'][$logic][] = [new Raw($field), $op, $condition];
1301
        return $this;
1302
    }
1303
1304
    /**
1305
     * 指定表达式查询条件
1306
     * @access public
1307
     * @param string $where 查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1308
     * @param array  $bind  参数绑定
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1309
     * @param string $logic 查询逻辑 and or xor
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1310
     * @return $this
1311
     */
1312
    public function whereRaw(string $where, array $bind = [], string $logic = 'AND')
1313
    {
1314
        if (!empty($bind)) {
1315
            $this->bindParams($where, $bind);
1316
        }
1317
1318
        $this->options['where'][$logic][] = new Raw($where);
1319
1320
        return $this;
1321
    }
1322
1323
    /**
1324
     * 指定表达式查询条件 OR
1325
     * @access public
1326
     * @param string $where 查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1327
     * @param array  $bind  参数绑定
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1328
     * @return $this
1329
     */
1330
    public function whereOrRaw(string $where, array $bind = [])
1331
    {
1332
        return $this->whereRaw($where, $bind, 'OR');
1333
    }
1334
1335
    /**
1336
     * 分析查询表达式
1337
     * @access protected
1338
     * @param string $logic     查询逻辑 and or xor
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1339
     * @param mixed  $field     查询字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1340
     * @param mixed  $op        查询表达式
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1341
     * @param mixed  $condition 查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1342
     * @param array  $param     查询参数
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1343
     * @param bool   $strict    严格模式
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1344
     * @return $this
1345
     */
1346
    protected function parseWhereExp(string $logic, $field, $op, $condition, array $param = [], bool $strict = false)
1347
    {
1348
        $logic = strtoupper($logic);
1349
1350
        if (is_string($field) && !empty($this->options['via']) && false === strpos($field, '.')) {
1351
            $field = $this->options['via'] . '.' . $field;
1352
        }
1353
1354
        if ($field instanceof Raw) {
1355
            return $this->whereRaw($field, is_array($op) ? $op : [], $logic);
1356
        } elseif ($strict) {
1357
            // 使用严格模式查询
1358
            if ('=' == $op) {
1359
                $where = $this->whereEq($field, $condition);
1360
            } else {
1361
                $where = [$field, $op, $condition, $logic];
1362
            }
1363
        } elseif (is_array($field)) {
1364
            // 解析数组批量查询
1365
            return $this->parseArrayWhereItems($field, $logic);
1366
        } elseif ($field instanceof Closure) {
1367
            $where = $field;
1368
        } elseif (is_string($field)) {
1369
            if (preg_match('/[,=\<\'\"\(\s]/', $field)) {
1370
                return $this->whereRaw($field, is_array($op) ? $op : [], $logic);
1371
            } elseif (is_string($op) && strtolower($op) == 'exp') {
1372
                $bind = isset($param[2]) && is_array($param[2]) ? $param[2] : [];
1373
                return $this->whereExp($field, $condition, $bind, $logic);
1374
            }
1375
1376
            $where = $this->parseWhereItem($logic, $field, $op, $condition, $param);
1377
        }
1378
1379
        if (!empty($where)) {
1380
            $this->options['where'][$logic][] = $where;
1381
        }
1382
1383
        return $this;
1384
    }
1385
1386
    /**
1387
     * 分析查询表达式
1388
     * @access protected
1389
     * @param string $logic     查询逻辑 and or xor
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1390
     * @param mixed  $field     查询字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1391
     * @param mixed  $op        查询表达式
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1392
     * @param mixed  $condition 查询条件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1393
     * @param array  $param     查询参数
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1394
     * @return array
1395
     */
1396
    protected function parseWhereItem(string $logic, $field, $op, $condition, array $param = []): array
1397
    {
1398
        if (is_array($op)) {
1399
            // 同一字段多条件查询
1400
            array_unshift($param, $field);
1401
            $where = $param;
1402
        } elseif ($field && is_null($condition)) {
1403
            if (is_string($op) && in_array(strtoupper($op), ['NULL', 'NOTNULL', 'NOT NULL'], true)) {
1404
                // null查询
1405
                $where = [$field, $op, ''];
1406
            } elseif ('=' === $op || is_null($op)) {
1407
                $where = [$field, 'NULL', ''];
1408
            } elseif ('<>' === $op) {
1409
                $where = [$field, 'NOTNULL', ''];
1410
            } else {
1411
                // 字段相等查询
1412
                $where = $this->whereEq($field, $op);
1413
            }
1414
        } elseif (in_array(strtoupper($op), ['EXISTS', 'NOT EXISTS', 'NOTEXISTS'], true)) {
1415
            $where = [$field, $op, is_string($condition) ? new Raw($condition) : $condition];
1416
        } else {
1417
            $where = $field ? [$field, $op, $condition, $param[2] ?? null] : [];
1418
        }
1419
1420
        return $where;
1421
    }
1422
1423
    /**
1424
     * 相等查询的主键处理
1425
     * @access protected
1426
     * @param string $field 字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1427
     * @param mixed  $value 字段值
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1428
     * @return array
1429
     */
1430
    protected function whereEq(string $field, $value): array
1431
    {
1432
        $where = [$field, '=', $value];
1433
        if ($this->getPk() == $field) {
1434
            $this->options['key'] = $value;
1435
        }
1436
1437
        return $where;
1438
    }
1439
1440
    /**
1441
     * 数组批量查询
1442
     * @access protected
1443
     * @param array  $field 批量查询
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1444
     * @param string $logic 查询逻辑 and or xor
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1445
     * @return $this
1446
     */
1447
    protected function parseArrayWhereItems(array $field, string $logic)
1448
    {
1449
        if (key($field) !== 0) {
1450
            $where = [];
1451
            foreach ($field as $key => $val) {
1452
                if ($val instanceof Raw) {
1453
                    $where[] = [$key, 'exp', $val];
1454
                } else {
1455
                    $where[] = is_null($val) ? [$key, 'NULL', ''] : [$key, is_array($val) ? 'IN' : '=', $val];
1456
                }
1457
            }
1458
        } else {
1459
            // 数组批量查询
1460
            $where = $field;
1461
        }
1462
1463
        if (!empty($where)) {
1464
            $this->options['where'][$logic] = isset($this->options['where'][$logic]) ? array_merge($this->options['where'][$logic], $where) : $where;
1465
        }
1466
1467
        return $this;
1468
    }
1469
1470
    /**
1471
     * 去除某个查询条件
1472
     * @access public
1473
     * @param string $field 查询字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1474
     * @param string $logic 查询逻辑 and or xor
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1475
     * @return $this
1476
     */
1477
    public function removeWhereField(string $field, string $logic = 'AND')
1478
    {
1479
        $logic = strtoupper($logic);
1480
1481
        if (isset($this->options['where'][$logic])) {
1482
            foreach ($this->options['where'][$logic] as $key => $val) {
1483
                if (is_array($val) && $val[0] == $field) {
1484
                    unset($this->options['where'][$logic][$key]);
1485
                }
1486
            }
1487
        }
1488
1489
        return $this;
1490
    }
1491
1492
    /**
1493
     * 去除查询参数
1494
     * @access public
1495
     * @param string $option 参数名 留空去除所有参数
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1496
     * @return $this
1497
     */
1498
    public function removeOption(string $option = '')
1499
    {
1500
        if ('' === $option) {
1501
            $this->options = [];
1502
            $this->bind    = [];
1503
        } elseif (isset($this->options[$option])) {
1504
            unset($this->options[$option]);
1505
        }
1506
1507
        return $this;
1508
    }
1509
1510
    /**
1511
     * 条件查询
1512
     * @access public
1513
     * @param mixed         $condition 满足条件(支持闭包)
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1514
     * @param Closure|array $query     满足条件后执行的查询表达式(闭包或数组)
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1515
     * @param Closure|array $otherwise 不满足条件后执行
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1516
     * @return $this
1517
     */
1518
    public function when($condition, $query, $otherwise = null)
1519
    {
1520
        if ($condition instanceof Closure) {
1521
            $condition = $condition($this);
1522
        }
1523
1524
        if ($condition) {
1525
            if ($query instanceof Closure) {
1526
                $query($this, $condition);
1527
            } elseif (is_array($query)) {
0 ignored issues
show
introduced by
The condition is_array($query) is always true.
Loading history...
1528
                $this->where($query);
1529
            }
1530
        } elseif ($otherwise) {
1531
            if ($otherwise instanceof Closure) {
1532
                $otherwise($this, $condition);
1533
            } elseif (is_array($otherwise)) {
0 ignored issues
show
introduced by
The condition is_array($otherwise) is always true.
Loading history...
1534
                $this->where($otherwise);
1535
            }
1536
        }
1537
1538
        return $this;
1539
    }
1540
1541
    /**
1542
     * 指定查询数量
1543
     * @access public
1544
     * @param int $offset 起始位置
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1545
     * @param int $length 查询数量
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1546
     * @return $this
1547
     */
1548
    public function limit(int $offset, int $length = null)
1549
    {
1550
        $this->options['limit'] = $offset . ($length ? ',' . $length : '');
1551
1552
        return $this;
1553
    }
1554
1555
    /**
1556
     * 指定分页
1557
     * @access public
1558
     * @param int $page     页数
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1559
     * @param int $listRows 每页数量
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1560
     * @return $this
1561
     */
1562
    public function page(int $page, int $listRows = null)
1563
    {
1564
        $this->options['page'] = [$page, $listRows];
1565
1566
        return $this;
1567
    }
1568
1569
    /**
1570
     * 分页查询
1571
     * @access public
1572
     * @param int|array $listRows 每页数量 数组表示配置参数
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1573
     * @param int|bool  $simple   是否简洁模式或者总记录数
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1574
     * @param array     $config   配置参数
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1575
     * @return Paginator
1576
     * @throws DbException
1577
     */
1578
    public function paginate($listRows = null, $simple = false, $config = [])
1579
    {
1580
        if (is_int($simple)) {
1581
            $total  = $simple;
1582
            $simple = false;
1583
        }
1584
1585
        $defaultConfig = [
1586
            'query'     => [], //url额外参数
1587
            'fragment'  => '', //url锚点
1588
            'var_page'  => 'page', //分页变量
1589
            'list_rows' => 15, //每页数量
1590
        ];
1591
1592
        if (is_array($listRows)) {
1593
            $config   = array_merge($defaultConfig, $listRows);
1594
            $listRows = intval($config['list_rows']);
1595
        } else {
1596
            $config   = array_merge($defaultConfig, $config);
1597
            $listRows = intval($listRows ?: $config['list_rows']);
1598
        }
1599
1600
        $page = isset($config['page']) ? (int) $config['page'] : Paginator::getCurrentPage($config['var_page']);
1601
1602
        $page = $page < 1 ? 1 : $page;
1603
1604
        $config['path'] = $config['path'] ?? Paginator::getCurrentPath();
1605
1606
        if (!isset($total) && !$simple) {
1607
            $options = $this->getOptions();
1608
1609
            unset($this->options['order'], $this->options['limit'], $this->options['page'], $this->options['field']);
1610
1611
            $bind    = $this->bind;
1612
            $total   = $this->count();
1613
            $results = $this->options($options)->bind($bind)->page($page, $listRows)->select();
1614
        } elseif ($simple) {
1615
            $results = $this->limit(($page - 1) * $listRows, $listRows + 1)->select();
1616
            $total   = null;
1617
        } else {
1618
            $results = $this->page($page, $listRows)->select();
1619
        }
1620
1621
        $this->removeOption('limit');
1622
        $this->removeOption('page');
1623
1624
        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...
1625
    }
1626
1627
    /**
1628
     * 表达式方式指定当前操作的数据表
1629
     * @access public
1630
     * @param mixed $table 表名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1631
     * @return $this
1632
     */
1633
    public function tableRaw(string $table)
1634
    {
1635
        $this->options['table'] = new Raw($table);
1636
1637
        return $this;
1638
    }
1639
1640
    /**
1641
     * 指定当前操作的数据表
1642
     * @access public
1643
     * @param mixed $table 表名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1644
     * @return $this
1645
     */
1646
    public function table($table)
1647
    {
1648
        if (is_string($table)) {
1649
            if (strpos($table, ')')) {
1650
                // 子查询
1651
            } elseif (false === strpos($table, ',')) {
1652
                if (strpos($table, ' ')) {
1653
                    list($item, $alias) = explode(' ', $table);
1654
                    $table              = [];
1655
                    $this->alias([$item => $alias]);
1656
                    $table[$item] = $alias;
1657
                }
1658
            } else {
1659
                $tables = explode(',', $table);
1660
                $table  = [];
1661
1662
                foreach ($tables as $item) {
1663
                    $item = trim($item);
1664
                    if (strpos($item, ' ')) {
1665
                        list($item, $alias) = explode(' ', $item);
1666
                        $this->alias([$item => $alias]);
1667
                        $table[$item] = $alias;
1668
                    } else {
1669
                        $table[] = $item;
1670
                    }
1671
                }
1672
            }
1673
        } elseif (is_array($table)) {
1674
            $tables = $table;
1675
            $table  = [];
1676
1677
            foreach ($tables as $key => $val) {
1678
                if (is_numeric($key)) {
1679
                    $table[] = $val;
1680
                } else {
1681
                    $this->alias([$key => $val]);
1682
                    $table[$key] = $val;
1683
                }
1684
            }
1685
        }
1686
1687
        $this->options['table'] = $table;
1688
1689
        return $this;
1690
    }
1691
1692
    /**
1693
     * USING支持 用于多表删除
1694
     * @access public
1695
     * @param mixed $using USING
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1696
     * @return $this
1697
     */
1698
    public function using($using)
1699
    {
1700
        $this->options['using'] = $using;
1701
        return $this;
1702
    }
1703
1704
    /**
1705
     * 存储过程调用
1706
     * @access public
1707
     * @param bool $procedure 是否为存储过程查询
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1708
     * @return $this
1709
     */
1710
    public function procedure(bool $procedure = true)
1711
    {
1712
        $this->options['procedure'] = $procedure;
1713
        return $this;
1714
    }
1715
1716
    /**
1717
     * 是否允许返回空数据(或空模型)
1718
     * @access public
1719
     * @param bool $allowEmpty 是否允许为空
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1720
     * @return $this
1721
     */
1722
    public function allowEmpty(bool $allowEmpty = true)
1723
    {
1724
        $this->options['allow_empty'] = $allowEmpty;
1725
        return $this;
1726
    }
1727
1728
    /**
1729
     * 指定排序 order('id','desc') 或者 order(['id'=>'desc','create_time'=>'desc'])
1730
     * @access public
1731
     * @param string|array|Raw $field 排序字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1732
     * @param string           $order 排序
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1733
     * @return $this
1734
     */
1735
    public function order($field, string $order = '')
1736
    {
1737
        if (empty($field)) {
1738
            return $this;
1739
        } elseif ($field instanceof Raw) {
1740
            $this->options['order'][] = $field;
1741
            return $this;
1742
        }
1743
1744
        if (is_string($field)) {
1745
            if (!empty($this->options['via'])) {
1746
                $field = $this->options['via'] . '.' . $field;
1747
            }
1748
            if (strpos($field, ',')) {
1749
                $field = array_map('trim', explode(',', $field));
1750
            } else {
1751
                $field = empty($order) ? $field : [$field => $order];
1752
            }
1753
        } elseif (!empty($this->options['via'])) {
1754
            foreach ($field as $key => $val) {
1755
                if (is_numeric($key)) {
1756
                    $field[$key] = $this->options['via'] . '.' . $val;
1757
                } else {
1758
                    $field[$this->options['via'] . '.' . $key] = $val;
1759
                    unset($field[$key]);
1760
                }
1761
            }
1762
        }
1763
1764
        if (!isset($this->options['order'])) {
1765
            $this->options['order'] = [];
1766
        }
1767
1768
        if (is_array($field)) {
1769
            $this->options['order'] = array_merge($this->options['order'], $field);
1770
        } else {
1771
            $this->options['order'][] = $field;
1772
        }
1773
1774
        return $this;
1775
    }
1776
1777
    /**
1778
     * 表达式方式指定Field排序
1779
     * @access public
1780
     * @param string $field 排序字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1781
     * @param array  $bind  参数绑定
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1782
     * @return $this
1783
     */
1784
    public function orderRaw(string $field, array $bind = [])
1785
    {
1786
        if (!empty($bind)) {
1787
            $this->bindParams($field, $bind);
1788
        }
1789
1790
        $this->options['order'][] = new Raw($field);
1791
1792
        return $this;
1793
    }
1794
1795
    /**
1796
     * 指定Field排序 orderField('id',[1,2,3],'desc')
1797
     * @access public
1798
     * @param string $field  排序字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1799
     * @param array  $values 排序值
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1800
     * @param string $order  排序 desc/asc
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1801
     * @return $this
1802
     */
1803
    public function orderField(string $field, array $values, string $order = '')
1804
    {
1805
        if (!empty($values)) {
1806
            $values['sort'] = $order;
1807
1808
            $this->options['order'][$field] = $values;
1809
        }
1810
1811
        return $this;
1812
    }
1813
1814
    /**
1815
     * 随机排序
1816
     * @access public
1817
     * @return $this
1818
     */
1819
    public function orderRand()
1820
    {
1821
        $this->options['order'][] = '[rand]';
1822
        return $this;
1823
    }
1824
1825
    /**
1826
     * 查询缓存
1827
     * @access public
1828
     * @param mixed             $key    缓存key
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1829
     * @param integer|\DateTime $expire 缓存有效期
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1830
     * @param string            $tag    缓存标签
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1831
     * @return $this
1832
     */
1833
    public function cache($key = true, $expire = null, string $tag = null)
1834
    {
1835
        if (false === $key) {
1836
            return $this;
1837
        }
1838
1839
        if ($key instanceof \DateTimeInterface || (is_int($key) && is_null($expire))) {
1840
            $expire = $key;
1841
            $key    = true;
1842
        }
1843
1844
        $this->options['cache'] = [$key, $expire, $tag];
1845
1846
        return $this;
1847
    }
1848
1849
    /**
1850
     * 指定group查询
1851
     * @access public
1852
     * @param string|array $group GROUP
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1853
     * @return $this
1854
     */
1855
    public function group($group)
1856
    {
1857
        $this->options['group'] = $group;
1858
        return $this;
1859
    }
1860
1861
    /**
1862
     * 指定having查询
1863
     * @access public
1864
     * @param string $having having
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1865
     * @return $this
1866
     */
1867
    public function having(string $having)
1868
    {
1869
        $this->options['having'] = $having;
1870
        return $this;
1871
    }
1872
1873
    /**
1874
     * 指定查询lock
1875
     * @access public
1876
     * @param bool|string $lock 是否lock
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1877
     * @return $this
1878
     */
1879
    public function lock($lock = false)
1880
    {
1881
        $this->options['lock'] = $lock;
1882
1883
        if ($lock) {
1884
            $this->options['master'] = true;
1885
        }
1886
1887
        return $this;
1888
    }
1889
1890
    /**
1891
     * 指定distinct查询
1892
     * @access public
1893
     * @param bool $distinct 是否唯一
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1894
     * @return $this
1895
     */
1896
    public function distinct(bool $distinct = true)
1897
    {
1898
        $this->options['distinct'] = $distinct;
1899
        return $this;
1900
    }
1901
1902
    /**
1903
     * 指定数据表别名
1904
     * @access public
1905
     * @param array|string $alias 数据表别名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1906
     * @return $this
1907
     */
1908
    public function alias($alias)
1909
    {
1910
        if (is_array($alias)) {
1911
            $this->options['alias'] = $alias;
1912
        } else {
1913
            $table = $this->getTable();
1914
1915
            $this->options['alias'][$table] = $alias;
1916
        }
1917
1918
        return $this;
1919
    }
1920
1921
    /**
1922
     * 指定强制索引
1923
     * @access public
1924
     * @param string $force 索引名称
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1925
     * @return $this
1926
     */
1927
    public function force(string $force)
1928
    {
1929
        $this->options['force'] = $force;
1930
        return $this;
1931
    }
1932
1933
    /**
1934
     * 查询注释
1935
     * @access public
1936
     * @param string $comment 注释
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1937
     * @return $this
1938
     */
1939
    public function comment(string $comment)
1940
    {
1941
        $this->options['comment'] = $comment;
1942
        return $this;
1943
    }
1944
1945
    /**
1946
     * 获取执行的SQL语句而不进行实际的查询
1947
     * @access public
1948
     * @param bool $fetch 是否返回sql
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1949
     * @return $this|Fetch
1950
     */
1951
    public function fetchSql(bool $fetch = true)
1952
    {
1953
        $this->options['fetch_sql'] = $fetch;
1954
1955
        if ($fetch) {
1956
            return new Fetch($this);
1957
        }
1958
1959
        return $this;
1960
    }
1961
1962
    /**
1963
     * 设置是否返回数组
1964
     * @access public
1965
     * @param bool $asArray 是否返回数组
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1966
     * @return $this
1967
     */
1968
    public function fetchArray(bool $asArray = true)
1969
    {
1970
        $this->options['array'] = $asArray;
1971
        return $this;
1972
    }
1973
1974
    /**
1975
     * 设置从主服务器读取数据
1976
     * @access public
1977
     * @param bool $readMaster 是否从主服务器读取
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1978
     * @return $this
1979
     */
1980
    public function master(bool $readMaster = true)
1981
    {
1982
        $this->options['master'] = $readMaster;
1983
        return $this;
1984
    }
1985
1986
    /**
1987
     * 设置是否严格检查字段名
1988
     * @access public
1989
     * @param bool $strict 是否严格检查字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1990
     * @return $this
1991
     */
1992
    public function strict(bool $strict = true)
1993
    {
1994
        $this->options['strict'] = $strict;
1995
        return $this;
1996
    }
1997
1998
    /**
1999
     * 设置查询数据不存在是否抛出异常
2000
     * @access public
2001
     * @param bool $fail 数据不存在是否抛出异常
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2002
     * @return $this
2003
     */
2004
    public function failException(bool $fail = true)
2005
    {
2006
        $this->options['fail'] = $fail;
2007
        return $this;
2008
    }
2009
2010
    /**
2011
     * 设置自增序列名
2012
     * @access public
2013
     * @param string $sequence 自增序列名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2014
     * @return $this
2015
     */
2016
    public function sequence(string $sequence = null)
2017
    {
2018
        $this->options['sequence'] = $sequence;
2019
        return $this;
2020
    }
2021
2022
    /**
2023
     * 设置是否REPLACE
2024
     * @access public
2025
     * @param bool $replace 是否使用REPLACE写入数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2026
     * @return $this
2027
     */
2028
    public function replace(bool $replace = true)
2029
    {
2030
        $this->options['replace'] = $replace;
2031
        return $this;
2032
    }
2033
2034
    /**
2035
     * 设置当前查询所在的分区
2036
     * @access public
2037
     * @param string|array $partition 分区名称
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2038
     * @return $this
2039
     */
2040
    public function partition($partition)
2041
    {
2042
        $this->options['partition'] = $partition;
2043
        return $this;
2044
    }
2045
2046
    /**
2047
     * 设置DUPLICATE
2048
     * @access public
2049
     * @param array|string|Raw $duplicate DUPLICATE信息
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2050
     * @return $this
2051
     */
2052
    public function duplicate($duplicate)
2053
    {
2054
        $this->options['duplicate'] = $duplicate;
2055
        return $this;
2056
    }
2057
2058
    /**
2059
     * 设置查询的额外参数
2060
     * @access public
2061
     * @param string $extra 额外信息
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2062
     * @return $this
2063
     */
2064
    public function extra(string $extra)
2065
    {
2066
        $this->options['extra'] = $extra;
2067
        return $this;
2068
    }
2069
2070
    /**
2071
     * 设置需要隐藏的输出属性
2072
     * @access public
2073
     * @param array $hidden 需要隐藏的字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2074
     * @return $this
2075
     */
2076
    public function hidden(array $hidden)
2077
    {
2078
        $this->options['hidden'] = $hidden;
2079
        return $this;
2080
    }
2081
2082
    /**
2083
     * 设置需要输出的属性
2084
     * @access public
2085
     * @param array $visible 需要输出的属性
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2086
     * @return $this
2087
     */
2088
    public function visible(array $visible)
2089
    {
2090
        $this->options['visible'] = $visible;
2091
        return $this;
2092
    }
2093
2094
    /**
2095
     * 设置需要追加输出的属性
2096
     * @access public
2097
     * @param array $append 需要追加的属性
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2098
     * @return $this
2099
     */
2100
    public function append(array $append)
2101
    {
2102
        $this->options['append'] = $append;
2103
        return $this;
2104
    }
2105
2106
    /**
2107
     * 设置JSON字段信息
2108
     * @access public
2109
     * @param array $json  JSON字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2110
     * @param bool  $assoc 是否取出数组
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2111
     * @return $this
2112
     */
2113
    public function json(array $json = [], bool $assoc = false)
2114
    {
2115
        $this->options['json']       = $json;
2116
        $this->options['json_assoc'] = $assoc;
2117
        return $this;
2118
    }
2119
2120
    /**
0 ignored issues
show
Coding Style introduced by
Parameter ...$args should have a doc-comment as per coding-style.
Loading history...
2121
     * 添加查询范围
2122
     * @access public
2123
     * @param array|string|Closure $scope 查询范围定义
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2124
     * @param array                $args  参数
1 ignored issue
show
Coding Style introduced by
Doc comment for parameter $args does not match actual variable name ...$args
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2125
     * @return $this
2126
     */
2127
    public function scope($scope, ...$args)
2128
    {
2129
        // 查询范围的第一个参数始终是当前查询对象
2130
        array_unshift($args, $this);
2131
2132
        if ($scope instanceof Closure) {
2133
            call_user_func_array($scope, $args);
2134
            return $this;
2135
        }
2136
2137
        if (is_string($scope)) {
2138
            $scope = explode(',', $scope);
2139
        }
2140
2141
        if ($this->model) {
2142
            // 检查模型类的查询范围方法
2143
            foreach ($scope as $name) {
2144
                $method = 'scope' . trim($name);
2145
2146
                if (method_exists($this->model, $method)) {
2147
                    call_user_func_array([$this->model, $method], $args);
2148
                }
2149
            }
2150
        }
2151
2152
        return $this;
2153
    }
2154
2155
    /**
2156
     * 指定数据表主键
2157
     * @access public
2158
     * @param string $pk 主键
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2159
     * @return $this
2160
     */
2161
    public function pk(string $pk)
2162
    {
2163
        $this->pk = $pk;
2164
        return $this;
2165
    }
2166
2167
    /**
2168
     * 添加日期或者时间查询规则
2169
     * @access public
2170
     * @param string       $name 时间表达式
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2171
     * @param string|array $rule 时间范围
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2172
     * @return $this
2173
     */
2174
    public function timeRule(string $name, $rule)
2175
    {
2176
        $this->timeRule[$name] = $rule;
2177
        return $this;
2178
    }
2179
2180
    /**
2181
     * 查询日期或者时间
2182
     * @access public
2183
     * @param string       $field 日期字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2184
     * @param string       $op    比较运算符或者表达式
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2185
     * @param string|array $range 比较范围
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2186
     * @param string       $logic AND OR
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2187
     * @return $this
2188
     */
2189
    public function whereTime(string $field, string $op, $range = null, string $logic = 'AND')
2190
    {
2191
        if (is_null($range) && isset($this->timeRule[$op])) {
2192
            $range = $this->timeRule[$op];
2193
            $op    = 'between';
2194
        }
2195
2196
        return $this->parseWhereExp($logic, $field, strtolower($op) . ' time', $range, [], true);
2197
    }
2198
2199
    /**
2200
     * 查询某个时间间隔数据
2201
     * @access public
2202
     * @param string $field    日期字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2203
     * @param string $start    开始时间
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2204
     * @param string $interval 时间间隔单位 day/month/year/week/hour/minute/second
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2205
     * @param int    $step     间隔
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2206
     * @param string $logic    AND OR
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2207
     * @return $this
2208
     */
2209
    public function whereTimeInterval(string $field, string $start, string $interval = 'day', int $step = 1, string $logic = 'AND')
2210
    {
2211
        $startTime = strtotime($start);
2212
        $endTime   = strtotime(($step > 0 ? '+' : '-') . abs($step) . ' ' . $interval . (abs($step) > 1 ? 's' : ''), $startTime);
2213
2214
        return $this->whereTime($field, 'between', $step > 0 ? [$startTime, $endTime] : [$endTime, $startTime], $logic);
2215
    }
2216
2217
    /**
2218
     * 查询月数据 whereMonth('time_field', '2018-1')
2219
     * @access public
2220
     * @param string $field 日期字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2221
     * @param string $month 月份信息
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2222
     * @param int    $step  间隔
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2223
     * @param string $logic AND OR
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2224
     * @return $this
2225
     */
2226
    public function whereMonth(string $field, string $month = 'this month', int $step = 1, string $logic = 'AND')
2227
    {
2228
        if (in_array($month, ['this month', 'last month'])) {
2229
            $month = date('Y-m', strtotime($month));
2230
        }
2231
2232
        return $this->whereTimeInterval($field, $month, 'month', $step, $logic);
2233
    }
2234
2235
    /**
2236
     * 查询周数据 whereWeek('time_field', '2018-1-1') 从2018-1-1开始的一周数据
2237
     * @access public
2238
     * @param string $field 日期字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2239
     * @param string $week  周信息
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2240
     * @param int    $step  间隔
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2241
     * @param string $logic AND OR
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2242
     * @return $this
2243
     */
2244
    public function whereWeek(string $field, string $week = 'this week', int $step = 1, string $logic = 'AND')
2245
    {
2246
        if (in_array($week, ['this week', 'last week'])) {
2247
            $week = date('Y-m-d', strtotime($week));
2248
        }
2249
2250
        return $this->whereTimeInterval($field, $week, 'week', $step, $logic);
2251
    }
2252
2253
    /**
2254
     * 查询年数据 whereYear('time_field', '2018')
2255
     * @access public
2256
     * @param string $field 日期字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2257
     * @param string $year  年份信息
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2258
     * @param int    $step     间隔
1 ignored issue
show
Coding Style introduced by
Expected 2 spaces after parameter name; 5 found
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2259
     * @param string $logic AND OR
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2260
     * @return $this
2261
     */
2262
    public function whereYear(string $field, string $year = 'this year', int $step = 1, string $logic = 'AND')
2263
    {
2264
        if (in_array($year, ['this year', 'last year'])) {
2265
            $year = date('Y', strtotime($year));
2266
        }
2267
2268
        return $this->whereTimeInterval($field, $year . '-1-1', 'year', $step, $logic);
2269
    }
2270
2271
    /**
2272
     * 查询日数据 whereDay('time_field', '2018-1-1')
2273
     * @access public
2274
     * @param string $field 日期字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2275
     * @param string $day   日期信息
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2276
     * @param int    $step     间隔
1 ignored issue
show
Coding Style introduced by
Expected 2 spaces after parameter name; 5 found
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2277
     * @param string $logic AND OR
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2278
     * @return $this
2279
     */
2280
    public function whereDay(string $field, string $day = 'today', int $step = 1, string $logic = 'AND')
2281
    {
2282
        if (in_array($day, ['today', 'yesterday'])) {
2283
            $day = date('Y-m-d', strtotime($day));
2284
        }
2285
2286
        return $this->whereTimeInterval($field, $day, 'day', $step, $logic);
2287
    }
2288
2289
    /**
2290
     * 查询日期或者时间范围 whereBetweenTime('time_field', '2018-1-1','2018-1-15')
2291
     * @access public
2292
     * @param string     $field     日期字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2293
     * @param string|int $startTime 开始时间
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2294
     * @param string|int $endTime   结束时间
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2295
     * @param string     $logic     AND OR
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2296
     * @return $this
2297
     */
2298
    public function whereBetweenTime(string $field, $startTime, $endTime, string $logic = 'AND')
2299
    {
2300
        return $this->whereTime($field, 'between', [$startTime, $endTime], $logic);
2301
    }
2302
2303
    /**
2304
     * 查询日期或者时间范围 whereNotBetweenTime('time_field', '2018-1-1','2018-1-15')
2305
     * @access public
2306
     * @param string     $field     日期字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2307
     * @param string|int $startTime 开始时间
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2308
     * @param string|int $endTime   结束时间
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2309
     * @return $this
2310
     */
2311
    public function whereNotBetweenTime(string $field, $startTime, $endTime)
2312
    {
2313
        return $this->whereTime($field, '<', $startTime)
2314
            ->whereTime($field, '>', $endTime);
2315
    }
2316
2317
    /**
2318
     * 查询当前时间在两个时间字段范围 whereBetweenTimeField('start_time', 'end_time')
2319
     * @access public
2320
     * @param string $startField 开始时间字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2321
     * @param string $endField   结束时间字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2322
     * @return $this
2323
     */
2324
    public function whereBetweenTimeField(string $startField, string $endField)
2325
    {
2326
        return $this->whereTime($startField, '<=', time())
2327
            ->whereTime($endField, '>=', time());
2328
    }
2329
2330
    /**
2331
     * 查询当前时间不在两个时间字段范围 whereNotBetweenTimeField('start_time', 'end_time')
2332
     * @access public
2333
     * @param string $startField 开始时间字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2334
     * @param string $endField   结束时间字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2335
     * @return $this
2336
     */
2337
    public function whereNotBetweenTimeField(string $startField, string $endField)
2338
    {
2339
        return $this->whereTime($startField, '>', time())
2340
            ->whereTime($endField, '<', time(), 'OR');
2341
    }
2342
2343
    /**
2344
     * 获取当前数据表的主键
2345
     * @access public
2346
     * @return string|array
2347
     */
2348
    public function getPk()
2349
    {
2350
        if (!empty($this->pk)) {
2351
            $pk = $this->pk;
2352
        } else {
2353
            $this->pk = $pk = $this->connection->getPk($this->getTable());
2354
        }
2355
2356
        return $pk;
2357
    }
2358
2359
    /**
2360
     * 批量参数绑定
2361
     * @access public
2362
     * @param array $value 绑定变量值
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2363
     * @return $this
2364
     */
2365
    public function bind(array $value)
2366
    {
2367
        $this->bind = array_merge($this->bind, $value);
2368
        return $this;
2369
    }
2370
2371
    /**
2372
     * 单个参数绑定
2373
     * @access public
2374
     * @param mixed   $value 绑定变量值
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2375
     * @param integer $type  绑定类型
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2376
     * @param string  $name  绑定标识
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2377
     * @return string
2378
     */
2379
    public function bindValue($value, int $type = null, string $name = null)
2380
    {
2381
        $name = $name ?: 'ThinkBind_' . (count($this->bind) + 1) . '_';
2382
2383
        $this->bind[$name] = [$value, $type ?: PDO::PARAM_STR];
2384
        return $name;
2385
    }
2386
2387
    /**
2388
     * 检测参数是否已经绑定
2389
     * @access public
2390
     * @param string $key 参数名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2391
     * @return bool
2392
     */
2393
    public function isBind($key)
2394
    {
2395
        return isset($this->bind[$key]);
2396
    }
2397
2398
    /**
2399
     * 参数绑定
2400
     * @access public
2401
     * @param string $sql  绑定的sql表达式
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2402
     * @param array  $bind 参数绑定
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2403
     * @return void
2404
     */
2405
    protected function bindParams(string &$sql, array $bind = []): void
2406
    {
2407
        foreach ($bind as $key => $value) {
2408
            if (is_array($value)) {
2409
                $name = $this->bindValue($value[0], $value[1], $value[2] ?? null);
2410
            } else {
2411
                $name = $this->bindValue($value);
2412
            }
2413
2414
            if (is_numeric($key)) {
2415
                $sql = substr_replace($sql, ':' . $name, strpos($sql, '?'), 1);
2416
            } else {
2417
                $sql = str_replace(':' . $key, ':' . $name, $sql);
2418
            }
2419
        }
2420
    }
2421
2422
    /**
2423
     * 查询参数批量赋值
2424
     * @access protected
2425
     * @param array $options 表达式参数
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2426
     * @return $this
2427
     */
2428
    protected function options(array $options)
2429
    {
2430
        $this->options = $options;
2431
        return $this;
2432
    }
2433
2434
    /**
2435
     * 获取当前的查询参数
2436
     * @access public
2437
     * @param string $name 参数名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2438
     * @return mixed
2439
     */
2440
    public function getOptions(string $name = '')
2441
    {
2442
        if ('' === $name) {
2443
            return $this->options;
2444
        }
2445
2446
        return $this->options[$name] ?? null;
2447
    }
2448
2449
    /**
2450
     * 设置当前的查询参数
2451
     * @access public
2452
     * @param string $option 参数名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2453
     * @param mixed  $value  参数值
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2454
     * @return $this
2455
     */
2456
    public function setOption(string $option, $value)
2457
    {
2458
        $this->options[$option] = $value;
2459
        return $this;
2460
    }
2461
2462
    /**
2463
     * 设置关联查询
2464
     * @access public
2465
     * @param array $relation 关联名称
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2466
     * @return $this
2467
     */
2468
    public function relation(array $relation)
2469
    {
2470
        if (!empty($relation)) {
2471
            $this->options['relation'] = $relation;
2472
        }
2473
2474
        return $this;
2475
    }
2476
2477
    /**
2478
     * 设置关联查询JOIN预查询
2479
     * @access public
2480
     * @param array|string $with 关联方法名称
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2481
     * @return $this
2482
     */
2483
    public function with($with)
2484
    {
2485
        if (!empty($with)) {
2486
            $this->options['with'] = (array) $with;
2487
        }
2488
2489
        return $this;
2490
    }
2491
2492
    /**
2493
     * 关联预载入 JOIN方式
2494
     * @access protected
2495
     * @param array|string $with     关联方法名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2496
     * @param string       $joinType JOIN方式
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2497
     * @return $this
2498
     */
2499
    public function withJoin($with, string $joinType = '')
2500
    {
2501
        if (empty($with)) {
2502
            return $this;
2503
        }
2504
2505
        $first = true;
2506
2507
        /** @var Model $class */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
2508
        $class = $this->model;
2509
        foreach ((array) $with as $key => $relation) {
2510
            $closure = null;
2511
            $field   = true;
2512
2513
            if ($relation instanceof Closure) {
2514
                // 支持闭包查询过滤关联条件
2515
                $closure  = $relation;
2516
                $relation = $key;
2517
            } elseif (is_array($relation)) {
2518
                $field    = $relation;
2519
                $relation = $key;
2520
            } elseif (is_string($relation) && strpos($relation, '.')) {
2521
                $relation = strstr($relation, '.', true);
2522
            }
2523
2524
            /** @var Relation $model */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
2525
            $relation = App::parseName($relation, 1, false);
2526
            $model    = $class->$relation();
2527
2528
            if ($model instanceof OneToOne) {
2529
                $model->eagerly($this, $relation, $field, $joinType, $closure, $first);
2530
                $first = false;
2531
            } else {
2532
                // 不支持其它关联
2533
                unset($with[$key]);
2534
            }
2535
        }
2536
2537
        $this->via();
2538
2539
        $this->options['with_join'] = $with;
2540
2541
        return $this;
2542
    }
2543
2544
    /**
2545
     * 设置数据字段获取器
2546
     * @access public
2547
     * @param string|array $name     字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2548
     * @param callable     $callback 闭包获取器
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2549
     * @return $this
2550
     */
2551
    public function withAttr($name, callable $callback = null)
2552
    {
2553
        if (is_array($name)) {
2554
            $this->options['with_attr'] = $name;
2555
        } else {
2556
            $this->options['with_attr'][$name] = $callback;
2557
        }
2558
2559
        return $this;
2560
    }
2561
2562
    /**
2563
     * 使用搜索器条件搜索字段
2564
     * @access public
2565
     * @param array  $fields 搜索字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2566
     * @param array  $data   搜索数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2567
     * @param string $prefix 字段前缀标识
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2568
     * @return $this
2569
     */
2570
    public function withSearch(array $fields, array $data = [], string $prefix = '')
2571
    {
2572
        foreach ($fields as $key => $field) {
2573
            if ($field instanceof Closure) {
2574
                $field($this, $data[$key] ?? null, $data, $prefix);
2575
            } elseif ($this->model) {
2576
                // 检测搜索器
2577
                $fieldName = is_numeric($key) ? $field : $key;
2578
                $method    = 'search' . App::parseName($fieldName, 1) . 'Attr';
2579
2580
                if (method_exists($this->model, $method)) {
2581
                    $this->model->$method($this, $data[$field] ?? null, $data, $prefix);
2582
                }
2583
            }
2584
        }
2585
2586
        return $this;
2587
    }
2588
2589
    /**
2590
     * 关联统计
2591
     * @access protected
2592
     * @param array|string $relations 关联方法名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2593
     * @param string       $aggregate 聚合查询方法
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2594
     * @param string       $field     字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2595
     * @param bool         $subQuery  是否使用子查询
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2596
     * @return $this
2597
     */
2598
    protected function withAggregate($relations, string $aggregate = 'count', $field = '*', bool $subQuery = true)
2599
    {
2600
        if (!$subQuery) {
2601
            $this->options['with_count'][] = [$relations, $aggregate, $field];
2602
        } else {
2603
            if (!isset($this->options['field'])) {
2604
                $this->field('*');
2605
            }
2606
2607
            foreach ((array) $relations as $key => $relation) {
2608
                $closure = $aggregateField = null;
2609
2610
                if ($relation instanceof Closure) {
2611
                    $closure  = $relation;
2612
                    $relation = $key;
2613
                } elseif (!is_int($key)) {
2614
                    $aggregateField = $relation;
2615
                    $relation       = $key;
2616
                }
2617
2618
                $relation = App::parseName($relation, 1, false);
2619
2620
                $count = '(' . $this->model->$relation()->getRelationCountQuery($closure, $aggregate, $field, $aggregateField) . ')';
2621
2622
                if (empty($aggregateField)) {
2623
                    $aggregateField = App::parseName($relation) . '_' . $aggregate;
2624
                }
2625
2626
                $this->field([$count => $aggregateField]);
2627
            }
2628
        }
2629
2630
        return $this;
2631
    }
2632
2633
    /**
2634
     * 关联统计
2635
     * @access public
2636
     * @param string|array $relation 关联方法名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2637
     * @param bool         $subQuery 是否使用子查询
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2638
     * @return $this
2639
     */
2640
    public function withCount($relation, bool $subQuery = true)
2641
    {
2642
        return $this->withAggregate($relation, 'count', '*', $subQuery);
2643
    }
2644
2645
    /**
2646
     * 关联统计Sum
2647
     * @access public
2648
     * @param string|array $relation 关联方法名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2649
     * @param string       $field    字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2650
     * @param bool         $subQuery 是否使用子查询
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2651
     * @return $this
2652
     */
2653
    public function withSum($relation, string $field, bool $subQuery = true)
2654
    {
2655
        return $this->withAggregate($relation, 'sum', $field, $subQuery);
2656
    }
2657
2658
    /**
2659
     * 关联统计Max
2660
     * @access public
2661
     * @param string|array $relation 关联方法名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2662
     * @param string       $field    字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2663
     * @param bool         $subQuery 是否使用子查询
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2664
     * @return $this
2665
     */
2666
    public function withMax($relation, string $field, bool $subQuery = true)
2667
    {
2668
        return $this->withAggregate($relation, 'max', $field, $subQuery);
2669
    }
2670
2671
    /**
2672
     * 关联统计Min
2673
     * @access public
2674
     * @param string|array $relation 关联方法名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2675
     * @param string       $field    字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2676
     * @param bool         $subQuery 是否使用子查询
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2677
     * @return $this
2678
     */
2679
    public function withMin($relation, string $field, bool $subQuery = true)
2680
    {
2681
        return $this->withAggregate($relation, 'min', $field, $subQuery);
2682
    }
2683
2684
    /**
2685
     * 关联统计Avg
2686
     * @access public
2687
     * @param string|array $relation 关联方法名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2688
     * @param string       $field    字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2689
     * @param bool         $subQuery 是否使用子查询
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2690
     * @return $this
2691
     */
2692
    public function withAvg($relation, string $field, bool $subQuery = true)
2693
    {
2694
        return $this->withAggregate($relation, 'avg', $field, $subQuery);
2695
    }
2696
2697
    /**
2698
     * 设置当前字段添加的表别名
2699
     * @access public
2700
     * @param string $via 临时表别名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2701
     * @return $this
2702
     */
2703
    public function via(string $via = '')
2704
    {
2705
        $this->options['via'] = $via;
2706
2707
        return $this;
2708
    }
2709
2710
    /**
2711
     * 保存记录 自动判断insert或者update
2712
     * @access public
2713
     * @param array $data        数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2714
     * @param bool  $forceInsert 是否强制insert
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2715
     * @return integer
2716
     */
2717
    public function save(array $data = [], bool $forceInsert = false)
2718
    {
2719
        if ($forceInsert) {
2720
            return $this->insert($data);
2721
        }
2722
2723
        $this->options['data'] = array_merge($this->options['data'] ?? [], $data);
2724
2725
        if (!empty($this->options['where'])) {
2726
            $isUpdate = true;
2727
        } else {
2728
            $isUpdate = $this->parseUpdateData($this->options['data']);
2729
        }
2730
2731
        return $isUpdate ? $this->update() : $this->insert();
2732
    }
2733
2734
    /**
2735
     * 插入记录
2736
     * @access public
2737
     * @param array   $data         数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2738
     * @param boolean $getLastInsID 返回自增主键
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2739
     * @return integer|string
2740
     */
2741
    public function insert(array $data = [], bool $getLastInsID = false)
2742
    {
2743
        if (!empty($data)) {
2744
            $this->options['data'] = $data;
2745
        }
2746
2747
        return $this->connection->insert($this, $getLastInsID);
2748
    }
2749
2750
    /**
2751
     * 插入记录并获取自增ID
2752
     * @access public
2753
     * @param array $data 数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2754
     * @return integer|string
2755
     */
2756
    public function insertGetId(array $data)
2757
    {
2758
        return $this->insert($data, true);
2759
    }
2760
2761
    /**
2762
     * 批量插入记录
2763
     * @access public
2764
     * @param array   $dataSet 数据集
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2765
     * @param integer $limit   每次写入数据限制
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2766
     * @return integer
2767
     */
2768
    public function insertAll(array $dataSet = [], int $limit = 0): int
2769
    {
2770
        if (empty($dataSet)) {
2771
            $dataSet = $this->options['data'] ?? [];
2772
        }
2773
2774
        if (empty($limit) && !empty($this->options['limit']) && is_numeric($this->options['limit'])) {
2775
            $limit = (int) $this->options['limit'];
2776
        }
2777
2778
        return $this->connection->insertAll($this, $dataSet, $limit);
2779
    }
2780
2781
    /**
2782
     * 通过Select方式插入记录
2783
     * @access public
2784
     * @param array  $fields 要插入的数据表字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2785
     * @param string $table  要插入的数据表名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2786
     * @return integer
2787
     * @throws PDOException
2788
     */
2789
    public function selectInsert(array $fields, string $table): int
2790
    {
2791
        return $this->connection->selectInsert($this, $fields, $table);
2792
    }
2793
2794
    /**
2795
     * 更新记录
2796
     * @access public
2797
     * @param mixed $data 数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2798
     * @return integer
2799
     * @throws Exception
2800
     * @throws PDOException
2801
     */
2802
    public function update(array $data = []): int
2803
    {
2804
        if (!empty($data)) {
2805
            $this->options['data'] = array_merge($this->options['data'] ?? [], $data);
2806
        }
2807
2808
        if (empty($this->options['where'])) {
2809
            $this->parseUpdateData($this->options['data']);
2810
        }
2811
2812
        if (empty($this->options['where']) && $this->model) {
2813
            $this->where($this->model->getWhere());
2814
        }
2815
2816
        if (empty($this->options['where'])) {
2817
            // 如果没有任何更新条件则不执行
2818
            throw new Exception('miss update condition');
2819
        }
2820
2821
        return $this->connection->update($this);
2822
    }
2823
2824
    /**
2825
     * 删除记录
2826
     * @access public
2827
     * @param mixed $data 表达式 true 表示强制删除
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2828
     * @return int
2829
     * @throws Exception
2830
     * @throws PDOException
2831
     */
2832
    public function delete($data = null): int
2833
    {
2834
        if (!is_null($data) && true !== $data) {
2835
            // AR模式分析主键条件
2836
            $this->parsePkWhere($data);
2837
        }
2838
2839
        if (empty($this->options['where']) && $this->model) {
2840
            $this->where($this->model->getWhere());
2841
        }
2842
2843
        if (true !== $data && empty($this->options['where'])) {
2844
            // 如果条件为空 不进行删除操作 除非设置 1=1
2845
            throw new Exception('delete without condition');
2846
        }
2847
2848
        if (!empty($this->options['soft_delete'])) {
2849
            // 软删除
2850
            list($field, $condition) = $this->options['soft_delete'];
2851
            if ($condition) {
2852
                unset($this->options['soft_delete']);
2853
                $this->options['data'] = [$field => $condition];
2854
2855
                return $this->connection->update($this);
2856
            }
2857
        }
2858
2859
        $this->options['data'] = $data;
2860
2861
        return $this->connection->delete($this);
2862
    }
2863
2864
    /**
2865
     * 执行查询但只返回PDOStatement对象
2866
     * @access public
2867
     * @return PDOStatement
2868
     */
2869
    public function getPdo(): PDOStatement
2870
    {
2871
        return $this->connection->pdo($this);
2872
    }
2873
2874
    /**
2875
     * 使用游标查找记录
2876
     * @access public
2877
     * @param mixed $data 数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2878
     * @return \Generator
2879
     */
2880
    public function cursor($data = null)
2881
    {
2882
        if (!is_null($data)) {
2883
            // 主键条件分析
2884
            $this->parsePkWhere($data);
2885
        }
2886
2887
        $this->options['data'] = $data;
2888
2889
        $connection = clone $this->connection;
2890
2891
        return $connection->cursor($this);
2892
    }
2893
2894
    /**
2895
     * 查找记录
2896
     * @access public
2897
     * @param mixed $data 数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2898
     * @return Collection|array|ModelCollection
2899
     * @throws DbException
2900
     * @throws ModelNotFoundException
2901
     * @throws DataNotFoundException
2902
     */
2903
    public function select($data = null)
2904
    {
2905
        if (!is_null($data)) {
2906
            // 主键条件分析
2907
            $this->parsePkWhere($data);
2908
        }
2909
2910
        $resultSet = $this->connection->select($this);
2911
2912
        // 返回结果处理
2913
        if (!empty($this->options['fail']) && count($resultSet) == 0) {
2914
            $this->throwNotFound();
2915
        }
2916
2917
        // 数据列表读取后的处理
2918
        if (!empty($this->model) && empty($this->options['array'])) {
2919
            // 生成模型对象
2920
            $resultSet = $this->resultSetToModelCollection($resultSet);
2921
        } else {
2922
            $this->resultSet($resultSet);
2923
        }
2924
2925
        return $resultSet;
2926
    }
2927
2928
    /**
2929
     * 查询数据转换为模型数据集对象
2930
     * @access protected
2931
     * @param array $resultSet 数据集
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2932
     * @return ModelCollection
2933
     */
2934
    protected function resultSetToModelCollection(array $resultSet): ModelCollection
2935
    {
2936
        if (!empty($this->options['collection']) && is_string($this->options['collection'])) {
2937
            $collection = $this->options['collection'];
2938
        }
2939
2940
        if (empty($resultSet)) {
2941
            return $this->model->toCollection([], $collection ?? null);
2942
        }
2943
2944
        // 检查动态获取器
2945
        if (!empty($this->options['with_attr'])) {
2946
            foreach ($this->options['with_attr'] as $name => $val) {
2947
                if (strpos($name, '.')) {
2948
                    list($relation, $field) = explode('.', $name);
2949
2950
                    $withRelationAttr[$relation][$field] = $val;
2951
                    unset($this->options['with_attr'][$name]);
2952
                }
2953
            }
2954
        }
2955
2956
        $withRelationAttr = $withRelationAttr ?? [];
2957
2958
        foreach ($resultSet as $key => &$result) {
2959
            // 数据转换为模型对象
2960
            $this->resultToModel($result, $this->options, true, $withRelationAttr);
2961
        }
2962
2963
        if (!empty($this->options['with'])) {
2964
            // 预载入
2965
            $result->eagerlyResultSet($resultSet, $this->options['with'], $withRelationAttr);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $result seems to be defined by a foreach iteration on line 2958. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
2966
        }
2967
2968
        if (!empty($this->options['with_join'])) {
2969
            // 预载入
2970
            $result->eagerlyResultSet($resultSet, $this->options['with_join'], $withRelationAttr, true);
2971
        }
2972
2973
        // 模型数据集转换
2974
        return $this->model->toCollection($resultSet, $collection ?? null);
2975
    }
2976
2977
    /**
2978
     * 处理数据集
2979
     * @access public
2980
     * @param array $resultSet 数据集
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2981
     * @return void
2982
     */
2983
    protected function resultSet(array &$resultSet): void
2984
    {
2985
        if (!empty($this->options['json'])) {
2986
            foreach ($resultSet as &$result) {
2987
                $this->jsonResult($result, $this->options['json'], true);
2988
            }
2989
        }
2990
2991
        if (!empty($this->options['with_attr'])) {
2992
            foreach ($resultSet as &$result) {
2993
                $this->getResultAttr($result, $this->options['with_attr']);
2994
            }
2995
        }
2996
2997
        if (!empty($this->options['visible']) || !empty($this->options['hidden'])) {
2998
            foreach ($resultSet as &$result) {
2999
                $this->filterResult($result);
3000
            }
3001
        }
3002
3003
        if (empty($this->options['array'])) {
3004
            // 返回Collection对象
3005
            $resultSet = new Collection($resultSet);
3006
        }
3007
    }
3008
3009
    /**
3010
     * 查找单条记录
3011
     * @access public
3012
     * @param mixed $data 查询数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3013
     * @return array|Model|null
3014
     * @throws DbException
3015
     * @throws ModelNotFoundException
3016
     * @throws DataNotFoundException
3017
     */
3018
    public function find($data = null)
3019
    {
3020
        if (!is_null($data)) {
3021
            // AR模式分析主键条件
3022
            $this->parsePkWhere($data);
3023
        }
3024
3025
        $result = $this->connection->find($this);
3026
3027
        // 数据处理
3028
        if (empty($result)) {
3029
            return $this->resultToEmpty();
3030
        }
3031
3032
        if (!empty($this->model) && empty($this->options['array'])) {
3033
            // 返回模型对象
3034
            $this->resultToModel($result, $this->options);
3035
        } else {
3036
            $this->result($result);
3037
        }
3038
3039
        return $result;
3040
    }
3041
3042
    /**
3043
     * 查找单条记录 不存在返回空数据(或者空模型)
3044
     * @access public
3045
     * @param mixed $data 数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3046
     * @return array|Model
3047
     */
3048
    public function findOrEmpty($data = null)
3049
    {
3050
        return $this->allowEmpty(true)->find($data);
3051
    }
3052
3053
    /**
3054
     * 处理空数据
3055
     * @access protected
3056
     * @return array|Model|null
3057
     * @throws DbException
3058
     * @throws ModelNotFoundException
3059
     * @throws DataNotFoundException
3060
     */
3061
    protected function resultToEmpty()
3062
    {
3063
        if (!empty($this->options['fail'])) {
3064
            $this->throwNotFound();
3065
        } elseif (!empty($this->options['allow_empty'])) {
3066
            return !empty($this->model) && empty($this->options['array']) ? $this->model->newInstance()->setQuery($this) : [];
3067
        } elseif (!empty($this->options['array'])) {
3068
            return [];
3069
        }
3070
    }
3071
3072
    /**
3073
     * 获取模型的更新条件
3074
     * @access protected
3075
     * @param array $options 查询参数
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3076
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
3077
    protected function getModelUpdateCondition(array $options)
3078
    {
3079
        return $options['where']['AND'] ?? null;
3080
    }
3081
3082
    /**
3083
     * 处理数据
3084
     * @access protected
3085
     * @param array $result 查询数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3086
     * @return void
3087
     */
3088
    protected function result(array &$result): void
3089
    {
3090
        if (!empty($this->options['json'])) {
3091
            $this->jsonResult($result, $this->options['json'], true);
3092
        }
3093
3094
        if (!empty($this->options['with_attr'])) {
3095
            $this->getResultAttr($result, $this->options['with_attr']);
3096
        }
3097
3098
        $this->filterResult($result);
3099
    }
3100
3101
    /**
3102
     * 处理数据的可见和隐藏
3103
     * @access protected
3104
     * @param array $result 查询数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3105
     * @return void
3106
     */
3107
    protected function filterResult(&$result): void
3108
    {
3109
        if (!empty($this->options['visible'])) {
3110
            foreach ($this->options['visible'] as $key) {
3111
                $array[] = $key;
3112
            }
3113
            $result = array_intersect_key($result, array_flip($array));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $array seems to be defined by a foreach iteration on line 3110. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
3114
        } elseif (!empty($this->options['hidden'])) {
3115
            foreach ($this->options['hidden'] as $key) {
3116
                $array[] = $key;
3117
            }
3118
            $result = array_diff_key($result, array_flip($array));
3119
        }
3120
    }
3121
3122
    /**
3123
     * 使用获取器处理数据
3124
     * @access protected
3125
     * @param array $result   查询数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3126
     * @param array $withAttr 字段获取器
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3127
     * @return void
3128
     */
3129
    protected function getResultAttr(array &$result, array $withAttr = []): void
3130
    {
3131
        foreach ($withAttr as $name => $closure) {
3132
            $name = App::parseName($name);
3133
3134
            if (strpos($name, '.')) {
3135
                // 支持JSON字段 获取器定义
3136
                list($key, $field) = explode('.', $name);
3137
3138
                if (isset($result[$key])) {
3139
                    $result[$key][$field] = $closure($result[$key][$field] ?? null, $result[$key]);
3140
                }
3141
            } else {
3142
                $result[$name] = $closure($result[$name] ?? null, $result);
3143
            }
3144
        }
3145
    }
3146
3147
    /**
3148
     * JSON字段数据转换
3149
     * @access protected
3150
     * @param array $result           查询数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3151
     * @param array $json             JSON字段
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3152
     * @param bool  $assoc            是否转换为数组
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3153
     * @param array $withRelationAttr 关联获取器
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3154
     * @return void
3155
     */
3156
    protected function jsonResult(array &$result, array $json = [], bool $assoc = false, array $withRelationAttr = []): void
3157
    {
3158
        foreach ($json as $name) {
3159
            if (!isset($result[$name])) {
3160
                continue;
3161
            }
3162
3163
            $result[$name] = json_decode($result[$name], true);
3164
3165
            if (isset($withRelationAttr[$name])) {
3166
                foreach ($withRelationAttr[$name] as $key => $closure) {
3167
                    $result[$name][$key] = $closure($result[$name][$key] ?? null, $result[$name]);
3168
                }
3169
            }
3170
3171
            if (!$assoc) {
3172
                $result[$name] = (object) $result[$name];
3173
            }
3174
        }
3175
    }
3176
3177
    /**
3178
     * 查询数据转换为模型对象
3179
     * @access protected
3180
     * @param array $result           查询数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3181
     * @param array $options          查询参数
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3182
     * @param bool  $resultSet        是否为数据集查询
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3183
     * @param array $withRelationAttr 关联字段获取器
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3184
     * @return void
3185
     */
3186
    protected function resultToModel(array &$result, array $options = [], bool $resultSet = false, array $withRelationAttr = []): void
3187
    {
3188
        // 动态获取器
3189
        if (!empty($options['with_attr']) && empty($withRelationAttr)) {
3190
            foreach ($options['with_attr'] as $name => $val) {
3191
                if (strpos($name, '.')) {
3192
                    list($relation, $field) = explode('.', $name);
3193
3194
                    $withRelationAttr[$relation][$field] = $val;
3195
                    unset($options['with_attr'][$name]);
3196
                }
3197
            }
3198
        }
3199
3200
        // JSON 数据处理
3201
        if (!empty($options['json'])) {
3202
            $this->jsonResult($result, $options['json'], $options['json_assoc'], $withRelationAttr);
3203
        }
3204
3205
        $result = $this->model->newInstance($result, $resultSet ? null : $this->getModelUpdateCondition($options))->setQuery($this);
3206
3207
        // 动态获取器
3208
        if (!empty($options['with_attr'])) {
3209
            $result->withAttribute($options['with_attr']);
3210
        }
3211
3212
        // 输出属性控制
3213
        if (!empty($options['visible'])) {
3214
            $result->visible($options['visible']);
3215
        } elseif (!empty($options['hidden'])) {
3216
            $result->hidden($options['hidden']);
3217
        }
3218
3219
        if (!empty($options['append'])) {
3220
            $result->append($options['append']);
3221
        }
3222
3223
        // 关联查询
3224
        if (!empty($options['relation'])) {
3225
            $result->relationQuery($options['relation'], $withRelationAttr);
3226
        }
3227
3228
        // 预载入查询
3229
        if (!$resultSet && !empty($options['with'])) {
3230
            $result->eagerlyResult($result, $options['with'], $withRelationAttr);
3231
        }
3232
3233
        // JOIN预载入查询
3234
        if (!$resultSet && !empty($options['with_join'])) {
3235
            $result->eagerlyResult($result, $options['with_join'], $withRelationAttr, true);
3236
        }
3237
3238
        // 关联统计
3239
        if (!empty($options['with_count'])) {
3240
            foreach ($options['with_count'] as $val) {
3241
                $result->relationCount($result, $val[0], $val[1], $val[2]);
3242
            }
3243
        }
3244
    }
3245
3246
    /**
3247
     * 查询失败 抛出异常
3248
     * @access protected
3249
     * @return void
3250
     * @throws ModelNotFoundException
3251
     * @throws DataNotFoundException
3252
     */
3253
    protected function throwNotFound(): void
3254
    {
3255
        if (!empty($this->model)) {
3256
            $class = get_class($this->model);
3257
            throw new ModelNotFoundException('model data Not Found:' . $class, $class, $this->options);
3258
        }
3259
3260
        $table = $this->getTable();
3261
        throw new DataNotFoundException('table data not Found:' . $table, $table, $this->options);
3262
    }
3263
3264
    /**
3265
     * 查找多条记录 如果不存在则抛出异常
3266
     * @access public
3267
     * @param array|string|Query|Closure $data 数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3268
     * @return array|PDOStatement|string|Model
3269
     * @throws DbException
3270
     * @throws ModelNotFoundException
3271
     * @throws DataNotFoundException
3272
     */
3273
    public function selectOrFail($data = null)
3274
    {
3275
        return $this->failException(true)->select($data);
3276
    }
3277
3278
    /**
3279
     * 查找单条记录 如果不存在则抛出异常
3280
     * @access public
3281
     * @param array|string|Query|Closure $data 数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3282
     * @return array|PDOStatement|string|Model
3283
     * @throws DbException
3284
     * @throws ModelNotFoundException
3285
     * @throws DataNotFoundException
3286
     */
3287
    public function findOrFail($data = null)
3288
    {
3289
        return $this->failException(true)->find($data);
3290
    }
3291
3292
    /**
3293
     * 分批数据返回处理
3294
     * @access public
3295
     * @param integer      $count    每次处理的数据数量
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3296
     * @param callable     $callback 处理回调方法
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3297
     * @param string|array $column   分批处理的字段名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3298
     * @param string       $order    字段排序
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3299
     * @return bool
3300
     * @throws DbException
3301
     */
3302
    public function chunk(int $count, callable $callback, $column = null, string $order = 'asc'): bool
3303
    {
3304
        $options = $this->getOptions();
3305
        $column  = $column ?: $this->getPk();
3306
3307
        if (isset($options['order'])) {
3308
            unset($options['order']);
3309
        }
3310
3311
        $bind = $this->bind;
3312
3313
        if (is_array($column)) {
3314
            $times = 1;
3315
            $query = $this->options($options)->page($times, $count);
3316
        } else {
3317
            $query = $this->options($options)->limit($count);
3318
3319
            if (strpos($column, '.')) {
3320
                list($alias, $key) = explode('.', $column);
3321
            } else {
3322
                $key = $column;
3323
            }
3324
        }
3325
3326
        $resultSet = $query->order($column, $order)->select();
3327
3328
        while (count($resultSet) > 0) {
3329
            if ($resultSet instanceof Collection) {
3330
                $resultSet = $resultSet->all();
3331
            }
3332
3333
            if (false === call_user_func($callback, $resultSet)) {
3334
                return false;
3335
            }
3336
3337
            if (isset($times)) {
3338
                $times++;
3339
                $query = $this->options($options)->page($times, $count);
3340
            } else {
3341
                $end    = end($resultSet);
3342
                $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...
3343
3344
                $query = $this->options($options)
3345
                    ->limit($count)
3346
                    ->where($column, 'asc' == strtolower($order) ? '>' : '<', $lastId);
3347
            }
3348
3349
            $resultSet = $query->bind($bind)->order($column, $order)->select();
3350
        }
3351
3352
        return true;
3353
    }
3354
3355
    /**
3356
     * 获取绑定的参数 并清空
3357
     * @access public
3358
     * @param bool $clear 是否清空绑定数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3359
     * @return array
3360
     */
3361
    public function getBind(bool $clear = true): array
3362
    {
3363
        $bind = $this->bind;
3364
        if ($clear) {
3365
            $this->bind = [];
3366
        }
3367
3368
        return $bind;
3369
    }
3370
3371
    /**
3372
     * 创建子查询SQL
3373
     * @access public
3374
     * @param bool $sub 是否添加括号
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3375
     * @return string
3376
     * @throws DbException
3377
     */
3378
    public function buildSql(bool $sub = true): string
3379
    {
3380
        return $sub ? '( ' . $this->fetchSql()->select() . ' )' : $this->fetchSql()->select();
3381
    }
3382
3383
    /**
3384
     * 视图查询处理
3385
     * @access protected
3386
     * @param array $options 查询参数
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3387
     * @return void
3388
     */
3389
    protected function parseView(array &$options): void
3390
    {
3391
        foreach (['AND', 'OR'] as $logic) {
3392
            if (isset($options['where'][$logic])) {
3393
                foreach ($options['where'][$logic] as $key => $val) {
3394
                    if (array_key_exists($key, $options['map'])) {
3395
                        array_shift($val);
3396
                        array_unshift($val, $options['map'][$key]);
3397
                        $options['where'][$logic][$options['map'][$key]] = $val;
3398
                        unset($options['where'][$logic][$key]);
3399
                    }
3400
                }
3401
            }
3402
        }
3403
3404
        if (isset($options['order'])) {
3405
            // 视图查询排序处理
3406
            foreach ($options['order'] as $key => $val) {
3407
                if (is_numeric($key) && is_string($val)) {
3408
                    if (strpos($val, ' ')) {
3409
                        list($field, $sort) = explode(' ', $val);
3410
                        if (array_key_exists($field, $options['map'])) {
3411
                            $options['order'][$options['map'][$field]] = $sort;
3412
                            unset($options['order'][$key]);
3413
                        }
3414
                    } elseif (array_key_exists($val, $options['map'])) {
3415
                        $options['order'][$options['map'][$val]] = 'asc';
3416
                        unset($options['order'][$key]);
3417
                    }
3418
                } elseif (array_key_exists($key, $options['map'])) {
3419
                    $options['order'][$options['map'][$key]] = $val;
3420
                    unset($options['order'][$key]);
3421
                }
3422
            }
3423
        }
3424
    }
3425
3426
    /**
3427
     * 分析数据是否存在更新条件
3428
     * @access public
3429
     * @param array $data 数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3430
     * @return bool
3431
     * @throws Exception
3432
     */
3433
    public function parseUpdateData(&$data): bool
3434
    {
3435
        $pk       = $this->getPk();
3436
        $isUpdate = false;
3437
        // 如果存在主键数据 则自动作为更新条件
3438
        if (is_string($pk) && isset($data[$pk])) {
3439
            $this->where($pk, '=', $data[$pk]);
3440
            $this->options['key'] = $data[$pk];
3441
            unset($data[$pk]);
3442
            $isUpdate = true;
3443
        } elseif (is_array($pk)) {
3444
            // 增加复合主键支持
3445
            foreach ($pk as $field) {
3446
                if (isset($data[$field])) {
3447
                    $this->where($field, '=', $data[$field]);
3448
                    $isUpdate = true;
3449
                } else {
3450
                    // 如果缺少复合主键数据则不执行
3451
                    throw new Exception('miss complex primary data');
3452
                }
3453
                unset($data[$field]);
3454
            }
3455
        }
3456
3457
        return $isUpdate;
3458
    }
3459
3460
    /**
3461
     * 把主键值转换为查询条件 支持复合主键
3462
     * @access public
3463
     * @param array|string $data 主键数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
3464
     * @return void
3465
     * @throws Exception
3466
     */
3467
    public function parsePkWhere($data): void
3468
    {
3469
        $pk = $this->getPk();
3470
3471
        if (is_string($pk)) {
3472
            // 获取数据表
3473
            if (empty($this->options['table'])) {
3474
                $this->options['table'] = $this->getTable();
3475
            }
3476
3477
            $table = is_array($this->options['table']) ? key($this->options['table']) : $this->options['table'];
3478
3479
            if (!empty($this->options['alias'][$table])) {
3480
                $alias = $this->options['alias'][$table];
3481
            }
3482
3483
            $key = isset($alias) ? $alias . '.' . $pk : $pk;
3484
            // 根据主键查询
3485
            if (is_array($data)) {
3486
                $this->where($key, 'in', $data);
3487
            } else {
3488
                $this->where($key, '=', $data);
3489
                $this->options['key'] = $data;
3490
            }
3491
        }
3492
    }
3493
3494
    /**
3495
     * 分析表达式(可用于查询或者写入操作)
3496
     * @access public
3497
     * @return array
3498
     */
3499
    public function parseOptions(): array
3500
    {
3501
        $options = $this->getOptions();
3502
3503
        // 获取数据表
3504
        if (empty($options['table'])) {
3505
            $options['table'] = $this->getTable();
3506
        }
3507
3508
        if (!isset($options['where'])) {
3509
            $options['where'] = [];
3510
        } elseif (isset($options['view'])) {
3511
            // 视图查询条件处理
3512
            $this->parseView($options);
3513
        }
3514
3515
        if (!isset($options['field'])) {
3516
            $options['field'] = '*';
3517
        }
3518
3519
        foreach (['data', 'order', 'join', 'union'] as $name) {
3520
            if (!isset($options[$name])) {
3521
                $options[$name] = [];
3522
            }
3523
        }
3524
3525
        if (!isset($options['strict'])) {
3526
            $options['strict'] = $this->connection->getConfig('fields_strict');
3527
        }
3528
3529
        foreach (['master', 'lock', 'fetch_sql', 'array', 'distinct', 'procedure'] as $name) {
3530
            if (!isset($options[$name])) {
3531
                $options[$name] = false;
3532
            }
3533
        }
3534
3535
        foreach (['group', 'having', 'limit', 'force', 'comment', 'partition', 'duplicate', 'extra'] as $name) {
3536
            if (!isset($options[$name])) {
3537
                $options[$name] = '';
3538
            }
3539
        }
3540
3541
        if (isset($options['page'])) {
3542
            // 根据页数计算limit
3543
            list($page, $listRows) = $options['page'];
3544
            $page                  = $page > 0 ? $page : 1;
3545
            $listRows              = $listRows ? $listRows : (is_numeric($options['limit']) ? $options['limit'] : 20);
3546
            $offset                = $listRows * ($page - 1);
3547
            $options['limit']      = $offset . ',' . $listRows;
3548
        }
3549
3550
        $this->options = $options;
3551
3552
        return $options;
3553
    }
3554
3555
    public function __debugInfo()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __debugInfo()
Loading history...
3556
    {
3557
        return [
3558
            'name'    => $this->name,
3559
            'pk'      => $this->pk,
3560
            'prefix'  => $this->prefix,
3561
            'bind'    => $this->bind,
3562
            'options' => $this->options,
3563
        ];
3564
    }
3565
}
3566