CreatorTrait.php
2.1 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
<?php
/**
* +--------------------------------------------------------------------------------------------------------------------
* trait :对象的用户和修改用户trait
* +--------------------------------------------------------------------------------------------------------------------
*
* @copyright Copyright
* @author Richer
* @package App\Models\Traits
* @version 2019年10月10日,18:12:16
* @link
*/
namespace App\Models\Traits;
use App\Models\User\User;
use Illuminate\Support\Facades\Schema;
/**
* Trait CreatorTrait.
*/
trait CreatorTrait
{
/**
* 在保存的时候自动创建
*
* @return void
*/
public static function bootHasCreator()
{
$user = auth('user')->user();
static::creating(function ($model) use ($user) {
$table = $model->getTable();
if (!$model->user_id && $user && Schema::hasColumn($table, 'user_id')) {
// 如果没有用户,默认设置为当前操作的用户
$model->user_id = $user->id;
}
// 设置 shop_id
if (!$model->created_by && $user && Schema::hasColumn($table, 'created_by')) {
$model->created_by = $user->id;
}
// 设置 shop_id
if (!$model->created_by && $user && Schema::hasColumn($table, 'created_model')) {
$model->created_model = $user::OBJ_NAME;
}
if (!$model->user_model && $user && Schema::hasColumn($table, 'user_model')) {
// 如果没有用户,默认设置为当前操作的用户
$model->user_model = 'user';
}
});
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function creator()
{
return $this->belongsTo(User::class, 'user_id');//->withTrashed();
}
/**
* @param User $user
*
* @return bool
*/
public function isCreatedBy($user)
{
if ($user instanceof User) {
$user = $user->id;
}
return $this->user_id == \intval($user);
}
}