Lae/app/Models/Task.php

99 lines
2.5 KiB
PHP
Raw Normal View History

2022-08-13 08:37:17 +00:00
<?php
2022-11-06 11:28:22 +00:00
namespace App\Models;
2022-08-13 08:37:17 +00:00
2023-01-10 12:47:14 +00:00
use App\Events\Users;
2022-08-26 14:37:20 +00:00
use App\Exceptions\CommonException;
2022-11-06 11:28:22 +00:00
use Illuminate\Database\Eloquent\Model;
2022-11-20 14:35:53 +00:00
use Illuminate\Database\Eloquent\Relations\BelongsTo;
2022-11-06 11:28:22 +00:00
use Illuminate\Support\Facades\Cache;
use Ramsey\Uuid\Uuid;
use function auth;
use function broadcast;
2022-08-13 08:37:17 +00:00
class Task extends Model
{
public $incrementing = false;
2022-08-26 14:37:20 +00:00
protected $fillable = [
'host_id',
'title',
'progress',
'status',
];
protected $casts = [
'id' => 'string',
'progress' => 'integer',
];
2022-09-08 18:35:00 +00:00
// key type string
protected $keyType = 'string';
2022-08-26 14:37:20 +00:00
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
// id 为 uuid
$model->id = Uuid::uuid4()->toString();
2022-11-20 14:35:53 +00:00
// 如果是模块创建的任务
if (auth('module')->check()) {
$model->module_id = auth('module')->id();
}
2022-09-08 18:35:00 +00:00
2022-08-26 14:37:20 +00:00
// host_id 和 user_id 至少存在一个
if (!$model->host_id && !$model->user_id) {
throw new CommonException('host_id 和 user_id 至少存在一个');
}
// if host_id
if ($model->host_id) {
$model->load('host');
2022-09-08 18:35:00 +00:00
if ($model->host === null) {
throw new CommonException('host_id 不存在');
}
2022-08-26 14:37:20 +00:00
$model->user_id = $model->host->user_id;
2022-09-10 04:03:20 +00:00
2022-09-11 12:44:43 +00:00
Cache::forget('user_tasks_' . $model->user_id);
2022-08-26 14:37:20 +00:00
}
});
2022-09-03 05:22:40 +00:00
2022-09-22 06:00:03 +00:00
// created
static::created(function ($model) {
$model->load('host');
2023-01-10 12:47:14 +00:00
broadcast(new Users($model->user_id, 'tasks.created', $model));
2022-09-22 06:00:03 +00:00
});
2023-01-10 13:42:27 +00:00
// updating
2022-09-03 05:22:40 +00:00
static::updating(function ($model) {
if ($model->progress == 100) {
$model->status = 'done';
}
});
2022-09-10 04:03:20 +00:00
// updated and delete
2022-09-11 12:44:43 +00:00
static::updated(function ($model) {
2022-11-06 11:28:22 +00:00
// Cache::forget('user_tasks_' . $model->user_id);
2022-09-22 06:00:03 +00:00
$model->load('host');
2023-01-10 12:47:14 +00:00
broadcast(new Users($model->user_id, 'tasks.updated', $model));
2022-09-10 04:03:20 +00:00
});
2022-09-11 12:44:43 +00:00
static::deleted(function ($model) {
2023-01-10 12:47:14 +00:00
broadcast(new Users($model->user_id, 'tasks.deleted', $model));
2022-09-10 04:03:20 +00:00
});
2022-08-26 14:37:20 +00:00
}
2022-11-20 14:35:53 +00:00
// public function scopeUser($query)
// {
// return $query->where('user_id', auth()->id());
// }
2022-11-20 14:35:53 +00:00
public function host(): BelongsTo
{
return $this->belongsTo(Host::class);
}
2022-08-13 08:37:17 +00:00
}