BaseModel.php
9.2 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
<?php
/**
+-----------------------------------------------------------------------------------------------------------------------
* 模型层基类:业务模型的基类,提供对数据库基本的增删改查类操作,不包含业务逻辑
+-----------------------------------------------------------------------------------------------------------------------
*
* PHP version 7
*
* @category App\Admin\Controllers
* @package App\Admin\Controllers
* @author Richer <yangzi1028@163.com>
* @date 2020年11月13日 01:26:09
* @copyright 2020-2022 Richer (http://www.Richer.com/)
* @license http://www.Richer.com/ License
* @link http://www.Richer.com/
*/
namespace App\Models;
use App\Models\Traits\ModelAppendFieldTrait;
use Encore\Admin\Traits\DefaultDatetimeFormat;
use Exception;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Spatie\Activitylog\Models\Activity as ActivityLog;
use App\Models\Traits\CreatorTrait;
use Illuminate\Database\Eloquent\Relations;
use Spatie\Activitylog\Traits\LogsActivity;
/**
* Class BaseModel
*
* @category App\Admin\Controllers
* @package App\Admin\Controllers
* @author Richer <yangzi1028@163.com>
* @date 2020年11月13日 01:26:09
* @copyright 2020-2022 Richer (http://www.Richer.com/)
* @license http://www.Richer.com/ License
* @link http://www.Richer.com/
*/
/**
* @property mixed id
* @property mixed sort
* @property mixed status
* @property mixed status_show
* @property mixed created_at
* @property mixed updated_at
*/
class BaseModel extends Model //implements HasMedia
{
use Notifiable, SoftDeletes, CreatorTrait, ModelAppendFieldTrait;
// use LogsActivity;
// add by Richer 于 2022年4月13日16:45:14 解决laravel-admin时间展示问题
use DefaultDatetimeFormat;
/**
* Remove flag in `has many` form.
* 在一对多模型使用的时候增加该变量,如果有该变量并且变量值为1,则代表该row将被删除
*/
const REMOVE_FLAG_NAME = '_remove_';
/**
* ADD flag in `has many` form.
* 在一对多模型使用的时候增加该变量,如果有该变量,则代表该row将被新增
*/
const ADD_FLAG_NAME = '_new_';
// 缓存时间
const CACHE_EXPIRY_SECOND = 10 * 60;
protected $guarded = ['id'];
protected $perPage = 10;
// 设置显示的最多数
protected $maxCount = 10000;
/**
* 需要被转换成日期的属性。
*
* @var array
*/
protected $dates = ['deleted_at'];
/**
* 列表查询字段
*
* @var array
*/
const LIST_QUERY_COLUMNS = ['*'];
/**
* 执行自定义的赋值
*
* @return void
*/
protected static function boot()
{
parent::boot();
self::bootHasCreator();
}
/**
* 方法:whereHas 的 where in 实现
*
* @param Builder $builder $builder
* @param string $relationName $relationName
* @param callable $callable $callable
*
* @return Builder
*
* @throws Exception
*/
public function scopeWhereHasIn($builder, $relationName, callable $callable)
{
$relationNames = explode('.', $relationName);
$nextRelation = implode('.', array_slice($relationNames, 1));
$method = $relationNames[0];
// @var Relations\BelongsTo|Relations\HasOne $relation
$relation = Relations\Relation::noConstraints(
function () use ($method) {
return $this->$method();
}
);
// @var Builder $in
$in = $relation->getQuery()->whereHasIn($nextRelation, $callable);
if ($relation instanceof Relations\BelongsTo) {
return $builder->whereIn($relation->getForeignKey(), $in->select($relation->getOwnerKey()));
} elseif ($relation instanceof Relations\HasOne) {
return $builder->whereIn($this->getKeyName(), $in->select($relation->getForeignKeyName()));
}
throw new Exception(__METHOD__ . " 不支持 " . get_class($relation));
}
/**
* 动态自定义字段赋值
*
* @param ActivityLog $activity $activity
* @param string $eventName $eventName
*
* @return void
*/
public function tapActivity(ActivityLog $activity, string $eventName)
{
//$activity->ip = Request::getClientIp();
}
/**
* 获取操作类型
*
* @param string $eventName 操作
*
* @return string
*/
public function getDescriptionForEvent(string $eventName): string
{
if ($eventName == 'created') {
return '添加';
}
if ($eventName == 'updated') {
return '更新';
}
if ($eventName == 'deleted') {
return '删除';
}
}
/**
* 自定义加密
*
* @param string $value 值
*
* @return mixed
*/
public function encrypt($value)
{
if ($value) {
return encrypt($value);
}
//base64_encode
return $value;
}
/**
* 自定义解密
*
* @param string $value 值
*
* @return mixed
*/
public function decrypt($value)
{
if ($value) {
try {
return decrypt($value);
} catch (DecryptException $e) {
return $value;
}
}
//base64_encode
return $value;
}
/**
* 批量新增数据
*
* @param array $data 数据
*
* @return bool
*/
public function addAll(Array $data)
{
$rs = DB::table($this->getTable())->insert($data);
return $rs;
}
/**
* 根据Id批量更新数据,可以放在model里面,使得每个model都是调用这个方法
*
* @param array $multipleData 数据
*
* @return bool
* @throws ValidationException
* @author Richer
*/
public function updateBatch($multipleData = array())
{
$tableName = $this->getTable();
if (!is_array($multipleData)) {
throw new ValidationException('must be an array', null, '6001');
}
foreach ($multipleData as &$row) {
if (!array_key_exists('id', $row)) {
throw new ValidationException('参数错误,缺少主键', null, '6001');
}
//$row[Model::FIELD_UPDATED_AT] = Carbon::now();
}
if ($tableName && !empty($multipleData)) {
$updateColumn = array_keys(\Arr::first($multipleData));
$referenceColumn = \Arr::first($updateColumn);
unset($updateColumn[0]);
$whereIn = "";
$q = "UPDATE " . $tableName . " SET ";
foreach ($updateColumn as $uColumn) {
$q .= $uColumn . " = CASE ";
foreach ($multipleData as $data) {
$q .= "WHEN " . $referenceColumn . " = " . $data[$referenceColumn] . " THEN '" . $data[$uColumn] . "' ";
}
$q .= "ELSE " . $uColumn . " END, ";
}
foreach ($multipleData as $data) {
$whereIn .= "'" . $data[$referenceColumn] . "', ";
}
$q = rtrim($q, ", ") . " WHERE " . $referenceColumn . " IN (" . rtrim($whereIn, ', ') . ")";
return \DB::update(\DB::raw($q));
} else {
return false;
}
}
/**
* 是否收藏
*
* @param null $favorites
* @return int
*/
public function isFavorited($favorites = null)
{
if (!$user = auth('user')->user()) {
return 0;
}
if ($favorites) {
if ($favorites->isEmpty()) {
return 0;
}
if ($is = $favorites->where('user_id', $user->id)->first()) {
return 1;
}
return 0;
} else {
if (!$user = auth('user')->user()) {
return 0;
}
return $hasFavorited = $user->hasFavorited($this) === true ? 1 : 0;
}
}
/**
* 是否点赞
*
* @param null $voters
* @return int
*/
public function isVoted($voters = null)
{
if ($voters) {
if ($voters->isNotEmpty()) {
return 1;
}
return 0;
} else {
if (!$user = auth('user')->user()) {
return 0;
}
return $hasUpvoted = $user->hasUpvoted($this) === true ? 1 : 0;
}
}
/**
* 是否被分销
*
* @param $distributions
* @return int
*/
public function isDistributed($distributions = null)
{
if ($distributions) {
if ($distributions->isNotEmpty()) {
return 1;
}
return 0;
} else {
if (!$user = auth('user')->user()) {
return 0;
}
return $this->isDistributedBy($user) ? 1 : 0;
}
}
}