Lae/app/Models/Workorder/Workorder.php

110 lines
2.5 KiB
PHP
Raw Normal View History

2022-08-13 06:04:47 +00:00
<?php
2022-08-13 06:12:37 +00:00
namespace App\Models\WorkOrder;
2022-08-13 06:04:47 +00:00
2022-08-13 08:37:17 +00:00
use App\Exceptions\CommonException;
2022-08-16 10:44:16 +00:00
use App\Models\Host;
use App\Models\Module\Module;
2022-08-13 08:37:17 +00:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
2022-08-16 10:44:16 +00:00
use Illuminate\Database\Eloquent\Model;
2022-08-13 06:04:47 +00:00
2022-08-13 06:12:37 +00:00
class WorkOrder extends Model
2022-08-13 06:04:47 +00:00
{
use HasFactory;
2022-08-13 06:12:37 +00:00
2022-08-15 14:29:57 +00:00
protected $table = 'work_orders';
2022-08-13 06:12:37 +00:00
protected $fillable = [
'title',
'content',
2022-08-13 08:37:17 +00:00
'host_id',
2022-08-13 06:12:37 +00:00
'user_id',
2022-08-15 14:29:57 +00:00
'module_id',
2022-08-13 06:12:37 +00:00
'status',
];
// replies
public function replies()
{
return $this->hasMany(Reply::class);
}
2022-08-13 08:37:17 +00:00
2022-08-15 14:29:57 +00:00
// host
2022-08-13 08:37:17 +00:00
public function host()
{
return $this->belongsTo(Host::class);
}
2022-08-15 14:29:57 +00:00
public function module()
{
return $this->belongsTo(Module::class);
}
// scope
public function scopeThisModule($query)
{
return $query->where('module_id', auth('remote')->id());
}
public function scopeUser($query)
{
return $query->where('user_id', auth()->id());
}
2022-08-13 08:37:17 +00:00
// on create
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
2022-08-15 14:29:57 +00:00
if ($model->host_id) {
$model->load(['host']);
$model->module_id = $model->host->module_id;
2022-08-13 08:37:17 +00:00
}
2022-08-15 14:29:57 +00:00
// if logged
if (auth('sanctum')->check()) {
$model->user_id = auth('sanctum')->id();
2022-08-13 08:37:17 +00:00
2022-08-15 14:29:57 +00:00
if ($model->host_id) {
if (!$model->user_id === $model->host->user_id) {
throw new CommonException('user_id not match host user_id');
}
}
2022-08-13 08:37:17 +00:00
} else {
2022-08-15 14:29:57 +00:00
throw new CommonException('user_id is required');
2022-08-13 08:37:17 +00:00
}
2022-08-15 14:29:57 +00:00
if ($model->host_id) {
$model->host->load('module');
$module = $model->host->module;
if ($module === null) {
$model->status = 'open';
} else {
$model->status = 'pending';
}
}
2022-08-13 08:37:17 +00:00
});
// 更新时获取差异部分
static::updating(function ($model) {
$original = $model->getOriginal();
// dd($original);
$diff = array_diff_assoc($model->attributes, $original);
// 如果更新了host_id则抛出异常
if (isset($diff['host_id'])) {
throw new CommonException('host_id cannot be updated');
}
// queue patch diff
});
}
2022-08-13 06:04:47 +00:00
}