Files
jandl-taskmanager-app/be/app/Models/SubTask.php
2023-02-27 22:43:27 +01:00

97 lines
2.5 KiB
PHP

<?php
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class SubTask extends Model
{
use HasFactory;
public $timestamps = true;
public $guarded = ['id'];
public function mastertask()
{
return $this->belongsTo(MasterTask::class, 'master_task_id');
}
public function user()
{
return $this->belongsTo(User::class);
}
public function timeblocks()
{
return $this->hasMany(Timeblock::class);
}
public function timesheets()
{
return $this->hasMany(Timesheet::class);
}
public function attachments()
{
return $this->hasMany(Attachment::class);
}
// syncnutie vykazu. ak array obsahuje NULL id, tak ho vytvori, ak obsahuje ID, tak ho upravi. ak sa v array nenachadza, tak ho zmaze z DB
public function syncTimesheets(Array $timesheets)
{
// pripravenie array na upsert
$timesheets = array_map(function($item) {
$item['user_id'] = $item['employee_id'];
unset($item['employee_id']);
unset($item['timestamp']);
$item['sub_task_id'] = $this->id;
if (!$this->id) {
$item['created_at'] = Carbon::now();
$item['updated_at'] = Carbon::now();
}
return $item;
}, $timesheets);
// zmazanie vykazov, ktore neboli poslane z frontendu
$this->timesheets()->whereNotIn('id', collect($timesheets)->pluck('id')->filter())->delete();
$this->timesheets()->upsert($timesheets, ['id']);
// kedze updatujem cez upsert, tak sa neaktualizuje updated_at. preto ho musim updatnut manualne
$this->touch();
}
public function syncTimeblocks(Array $timeblocks)
{
if (empty($timeblocks)) {
return $this->timeblocks()->delete();
}
// pripravenie array na upsert
$timeblocks = array_map(function($item) {
$item['sub_task_id'] = $this->id;
return $item;
}, $timeblocks);
// zmazanie vykazov, ktore neboli poslane z frontendu
$this->timeblocks()->whereNotIn('id', collect($timeblocks)->pluck('id')->filter())->delete();
$this->timeblocks()->upsert($timeblocks, ['id']);
}
public function deleteAttachments()
{
foreach ( $this->attachments as $attachment ) {
$attachment->deleteFromS3();
}
$this->attachments()->delete();
return true;
}
}