<?php
class CommonCategoryModel extends Model {
/**
* 获取孩子节点
* all==false时,只获取直接子节点,
* self==false时,不包括本身
*
*
* @param unknown_type $id
* @param unknown_type $all
*/
public function getChildren($id,$self=true,$all=true) {
if(intval($id)){
$category =$this->find($id);
$left = $category['left'];
$right = $category['right'];
$level = $category['level'];
$where = "`left` BETWEEN $left AND $right";
if(!$all){
//不取所有,只取直接孩子
$where .=" and level = $level+1";
}
if(!$self){
//不包括本身
$where .=" and level > $level";
}
return $this->where($where)->order('`left` asc')->select();
}
}
/**
* 获取父类节点,若是all==false,则只取直接父类节点
* self==false,不包括本身
*
* @param unknown_type $id
* @param unknown_type $self
* @param unknown_type $all
*/
public function getParents($id,$self=false,$all=true,$root = false){
if(intval($id)){
$category =$this->find($id);
$left = $category['left'];
$right = $category['right'];
$level = $category['level'];
if($level>0){
if(!$self){
$where = "`left` < $left AND `right` > $right";
}else{
$where = "`left` <= $left AND `right` >= $right";
}
if(!$root){
$where .= " and level!=0";
}
if(!$all){
$where .=" and level = $level-1";
}
return $this->where($where)->order('`left` asc')->select();
}else{
if($self){
return $category;
}else{
return null;
}
}
}
}
/**
* 增长子节点
*
* @param unknown_type $id
* @param unknown_type $childName
* @return unknown
*/
public function addChild($id,$childName){
if(intval($id)){
$category =$this->find($id);
$left = $category['left'];
$right = $category['right'];
$level = $category['level'];
$this->query("UPDATE __TABLE__ SET `left`=`left`+2 WHERE `left` >$right");
$this->query("UPDATE __TABLE__ SET `right`=`right`+2 WHERE `right`>=$right");
$data['left'] = $right;
$data['right'] = $right+1;
$data['level'] = $level+1;
$data['name'] = $childName;
return $this->add($data);
}
}
/**
* 删除节点
*
* @param unknown_type $id
*/
public function deleteNode($id){
if($id === 1 ){
//若是是根目录,设定为不可删除
return false;
//$thi->query("truncate table __TABLE__ ");
}else{
$category =$this->find($id);
$left = $category['left'];
$right = $category['right'];
$level = $category['level'];
if($level ==0){//仍然是根节点
// $this->query("truncate table __TABLE__ ");
return false;
}
//非根节点,且存在,删除本身以及其子孙
$this->where("`left`>={$left} and `right`<=$right")->delete();
//更新左右值
$value=$right-$left+1;
$this->query("UPDATE __TABLE__ SET `left` =`left` - $value WHERE `left`> $left");
$this->query("UPDATE __TABLE__ SET `right`=`right`- $value WHERE `right`>$right");
}
}
public function getModelName() {
return substr(get_class($this),0,-5);
}
}
?>php
使用:this
其余的model extends commonCategoryModelget