QR_code_generator/app/Support/HasObjectsTrait.php

50 lines
1.7 KiB
PHP

<?php
namespace App\Support;
use App\Models\Objects\NirObject;
use App\Models\Objects\ObjectType;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
trait HasObjectsTrait {
public function objects(): MorphToMany {
return $this->morphToMany(NirObject::class, 'objectable')->orderByPivot('ord')->withTimestamps();
}
public function getObjectAttribute() {
return $this->objects()->first();
}
public function getObject($typeName): ?Model {
return ($type = ObjectType::query()->where(['name' => $typeName])->first()) ? $this->objects()->firstOrCreate(['type_id' => $type->id]) : null;
}
public function createObject($typeName, $ord = null): ?Model {
if (($type = ObjectType::query()->where(['name' => $typeName])->first()) && ($object = NirObject::create(['type_id' => $type->id]))) {
if ($ord !== null) $ord = ($res = $this->objects()->where(['type_id' => $type->id])->withPivot('ord')->reorder()->orderByPivot('ord', 'desc')->first()) ? ($res->pivot->ord + 1) : 0;
$this->objects()->attach($object->id, ['ord' => $ord]);
return $object;
}
return null;
}
public function getValue($fieldName) {
return $this->object ? $this->object->getValue($fieldName) : null;
}
public function setValue($fieldName, $value) {
return $this->object ? $this->object->setValue($fieldName, $value) : null;
}
public function setValues(array $values) {
return $this->object ? $this->object->setValues($values) : null;
}
public function addValue($fieldName, $value) {
return $this->object ? $this->object->addValue($fieldName, $value) : null;
}
}