|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Date: 2019/2/27 Time: 10:48 |
|
4
|
|
|
* |
|
5
|
|
|
* @author Eddy <[email protected]> |
|
6
|
|
|
* @version v1.0.0 |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace App\Repository; |
|
10
|
|
|
|
|
11
|
|
|
use Carbon\Carbon; |
|
12
|
|
|
use Illuminate\Database\Eloquent\Builder; |
|
13
|
|
|
|
|
14
|
|
|
trait Searchable |
|
15
|
|
|
{ |
|
16
|
|
|
public static function buildQuery(Builder $query, array $condition) |
|
17
|
|
|
{ |
|
18
|
|
|
// 获取模型定义的搜索域 |
|
19
|
|
|
$model = $query->getModel(); |
|
20
|
|
|
$searchField = []; |
|
21
|
|
|
if (property_exists($model, 'searchField')) { |
|
22
|
|
|
$searchField = $model::$searchField; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
foreach ($condition as $k => $v) { |
|
26
|
|
|
if (!is_array($v) && isset($searchField[$k]['searchType'])) { |
|
27
|
|
|
$condition[$k] = [$searchField[$k]['searchType'], $v]; |
|
28
|
|
|
} |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
foreach ($condition as $k => $v) { |
|
32
|
|
|
$type = 'like'; |
|
33
|
|
|
$value = $v; |
|
34
|
|
|
if (is_array($v)) { |
|
35
|
|
|
list($type, $value) = $v; |
|
36
|
|
|
} |
|
37
|
|
|
$value = trim($value); |
|
38
|
|
|
// 搜索值为空字符串则忽略该条件 |
|
39
|
|
|
if ($value === '') { |
|
40
|
|
|
continue; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
if ($k === 'created_at' || |
|
44
|
|
|
$k === 'updated_at' || |
|
45
|
|
|
(isset($searchField[$k]['showType']) && $searchField[$k]['showType'] === 'datetime') |
|
46
|
|
|
) { |
|
47
|
|
|
$dates = explode(' ~ ', $value); |
|
48
|
|
|
if (count($dates) === 2) { |
|
49
|
|
|
$query->whereBetween($k, [ |
|
50
|
|
|
Carbon::parse($dates[0])->startOfDay(), |
|
51
|
|
|
Carbon::parse($dates[1])->endOfDay(), |
|
52
|
|
|
]); |
|
53
|
|
|
} |
|
54
|
|
|
} elseif (isset($searchField[$k]['searchType']) && $searchField[$k]['searchType'] === 'whereRaw') { |
|
55
|
|
|
$queryParams = array_pad([], substr_count($searchField[$k]['searchCondition'], '?'), $value); |
|
56
|
|
|
$query->whereRaw($searchField[$k]['searchCondition'], $queryParams); |
|
57
|
|
|
} else { |
|
58
|
|
|
$query->where($k, $type, $type === 'like' ? "%{$value}%" : $value); |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|