servermgrv2/app/Models/BaseHierarchyModel.php
2023-07-26 10:30:51 +09:00

65 lines
2.2 KiB
PHP

<?php
namespace App\Models;
use App\Entities\BaseEntity;
//계층형구조구현용 모델(게시판,카테고리 등등)
abstract class BaseHierarchyModel extends BaseModel
{
protected function __construct()
{
parent::__construct();
$this->allowedFields = [...$this->allowedFields, "grpno", "grporder", "grpdepth"];
}
abstract function reply($parent_entity, array $formDatas): BaseEntity;
protected function getFieldRule(string $field, array $rules, string $action = ""): array
{
switch ($field) {
case "grpno":
case "grporder":
case "grpdepth":
$rules[$field] = "if_exist|numeric";
break;
default:
$rules = parent::getFieldRule($field, $rules, $action);
break;
}
return $rules;
}
final protected function create_process($entity, array $formDatas)
{
$entity = parent::create_process($entity, $formDatas);
//생성시는 grpno가 primarykey와 같음
$this->builder()->set("grpno", $entity->getPrimaryKey());
$this->builder()->where($this->primaryKey, $entity->getPrimaryKey());
$this->builder()->update();
return $entity;
}
final protected function reply_process($parent_entity, $entity, array $formDatas)
{
//부모의 그룹과 grpno가 같고, 부모의 grporder보다 1 큰것을 grporder+1을 해서 update
//escape -> false옵션 반드시 있어야함
$this->builder()->set("grporder", "grporder+1", false);
$this->builder()->where([
"grpno" => $parent_entity->grpno,
"grporder >" => $parent_entity->grporder
]);
$this->builder()->update();
//reply용 설정
$entity->grpno = $parent_entity->grpno;
$entity->grporder = $parent_entity->grporder + 1;
$entity->grpdepth = $parent_entity->grpdepth + 1;
return parent::create_process($entity, $formDatas);
}
public function setIndexOrderBy($field, $order = "DESC")
{
parent::setIndexOrderBy($field, $order);
$this->orderBy("grpno", "DESC");
$this->orderBy("grporder", "ASC");
}
}