ModelExtend.php
2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<?php
namespace addons\exam\traits;
use think\Db;
/**
* Trait ModelExtend
* 自封装的模型扩展
* 基本来源于Laravel操作
* by zgc
*/
trait ModelExtend
{
/**
* 获取对象,空直接抛错
*
* @param integer $pk 主键
* @param string $message 提示的错误信息
* @param array $with 预加载
*/
public static function findOrFail(int $pk, string $message = '数据不存在', $with = []): self
{
if (!$pk) {
fail('缺少主键信息');
}
$model = $with ? self::with($with)->find($pk) : self::get($pk);
if (!$model) {
fail($message);
}
return $model;
}
/**
* 更新或创建
* @param array $attributes 条件
* @param array $values 值
* @return mixed
*/
public static function updateOrCreate(array $attributes, array $values = [], string $type = 'count')
{
$self = new static();
// $model = $self->where($attributes)->find();
$model = $self::get($attributes);
if ($model) {
$model->data($values, true);
} else {
$model = new static();
$model->data($values);
}
$count = $model->allowField(true)->save();
if ($type == 'count') {
return $count;
}
return $model;
}
/**
* 批量插入或更新
* @param array $values
*/
public static function upsert(array $values, $pk = 'id')
{
Db::transaction(function () use ($values, $pk) {
collection($values)->each(function ($item) use ($pk) {
$id = isset($item[$pk]) ? $item[$pk] : 0;
self::updateOrCreate(
[$pk => $id],
$item
);
});
});
}
/**
* 只取模型部分key数据
* @param array $keys
* @return array
*/
public function only(array $keys): array
{
// return only_keys($this->toArray(), $keys);
$result = [];
foreach ($this->toArray() as $k => $value) {
if (in_array($k, $keys)) {
$result[$k] = $value;
}
}
return $result;
}
/**
* 隐藏模型部分key数据
* @param array $keys
* @return array
*/
public function makeHidden(array $keys): array
{
// return only_keys($this->toArray(), $keys);
$result = [];
foreach ($this->toArray() as $k => $value) {
if (in_array($k, $keys)) {
unset($value[$k]);
$result[$k] = $value;
}
}
return $result;
}
}