Lae/app/Models/User/Task.php

107 lines
2.3 KiB
PHP
Raw Normal View History

2022-08-13 08:37:17 +00:00
<?php
namespace App\Models\User;
2022-08-26 14:37:20 +00:00
use App\Models\Host;
use App\Exceptions\CommonException;
2022-08-13 08:37:17 +00:00
use Illuminate\Database\Eloquent\Model;
2022-08-26 14:37:20 +00:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
2022-09-10 04:03:20 +00:00
use Illuminate\Support\Facades\Cache;
2022-08-26 14:37:20 +00:00
use Ramsey\Uuid\Uuid;
2022-08-13 08:37:17 +00:00
class Task extends Model
{
use HasFactory;
2022-08-26 14:37:20 +00:00
protected $fillable = [
'host_id',
'title',
'progress',
'status',
];
protected $casts = [
'id' => 'string',
'progress' => 'integer',
];
public $incrementing = false;
2022-09-08 18:35:00 +00:00
// key type string
protected $keyType = 'string';
public function scopeUser($query)
{
2022-08-26 14:37:20 +00:00
return $query->where('user_id', auth()->id());
}
2022-09-10 04:03:20 +00:00
public function getCurrentUserTasks()
{
return Cache::remember('user_tasks_' . auth()->id(), 3600, function () {
return $this->user()->with('host')->get();
});
}
2022-09-08 18:35:00 +00:00
public function host()
{
2022-08-26 14:37:20 +00:00
return $this->belongsTo(Host::class);
}
// before create
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
// id 为 uuid
$model->id = Uuid::uuid4()->toString();
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 不存在');
}
// dd($model);
2022-08-26 14:37:20 +00:00
// dd($model->host_id);
// $host = Host::where('id', $model->host_id)->first();
// dd($host);
2022-09-08 18:35:00 +00:00
2022-08-26 14:37:20 +00:00
$model->user_id = $model->host->user_id;
2022-09-10 04:03:20 +00:00
Cache::forget('user_tasks_' . auth()->id());
2022-08-26 14:37:20 +00:00
}
});
2022-09-03 05:22:40 +00:00
// updateing
static::updating(function ($model) {
if ($model->progress == 100) {
$model->status = 'done';
}
});
2022-09-10 04:03:20 +00:00
// updated and delete
static::updated(function () {
Cache::forget('user_tasks_' . auth()->id());
});
static::deleted(function () {
Cache::forget('user_tasks_' . auth()->id());
});
2022-08-26 14:37:20 +00:00
}
2022-08-13 08:37:17 +00:00
}