CI 묻고 답하기

제목 멀티형 분류 어떻게들 만드시나요 ?
글쓴이 람이 작성시각 2014/09/25 14:19:53
댓글 : 3 추천 : 0 스크랩 : 0 조회수 : 16410   RSS
제가 부족한 실력으로 카테고리를 만들어 보고 있는데 (쇼핑몰에 쓸) 이게 답은 아닌듯 해서요...

어거지로 만들고 있다는 느낌이 드네요.,

컨트롤러
   case 'category':
    $this->load->model('admin_shm');
    if( $this->input->get_post('id',TRUE) ) {
     $data['ca_value'] = $this->admin_shm->ca_name($this->input->get_post('id',TRUE));
    }
    $data['list'] = $this->admin_shm->ca_getDB('lio_category','','');
    $page = 'shop/category_list';
    $data['nav'] = array('0'=>'분류 관리','1'=>'분류 목록');
    break;
   case 'category_ok':
    $this->load->library('form_validation');
    $this->form_validation->set_error_delimiters('<span class="text-red">', '</span>');
    $this->form_validation->set_rules('ca_name', '분류명', 'trim|required|min_length[1]|max_length[255]|xss_clean');
     
    if ($this->form_validation->run() == FALSE) {
     alert_back('분류명이 비어 있습니다.');
     return false;
    } else {
     $this->load->model('admin_shm');
     $query = $this->admin_shm->ca_insert();
     if($query) {
      redirect('/admin/shop/category/'.$this->input->post('sh_id',TRUE));
     } else {
      alert('디비에 저장하지 못했습니다.');
     }
    }
    break;
   case 'addca':
    $ca_id = $this->input->post('msg');
    if(strlen($ca_id)==3) {
     echo "
     <select name='sel2' id='sel2' onchange='sub(2)'>
     <option value=''>::중분류 선택::</option>";
     $this->load->model('admin_shm');
     $user = $this->admin_shm->getDB('lio_category','ca_id',$ca_id);
     foreach($user as $d) {
      echo "<option value='{$d->ca_id}'>{$d->ca_name}</option>";
     }
     echo "</select>";
    } else if(strlen($ca_id)==6) {
     echo "
     <select name='sel3' id='sel3' onchange='sub(3)'>
     <option value=''>::소분류 선택::</option>";
     $this->load->model('admin_shm');
     $user = $this->admin_shm->getDB('lio_category','ca_id',$ca_id);
     foreach($user as $d) {
      echo "<option value='{$d->ca_id}'>{$d->ca_name}</option>";
     }
     echo "</select>";
    } else if(strlen($ca_id)==9) {
     echo "
     <select name='sel4' id='sel4' onchange='sub(4)'>
     <option value=''>::최종분류 선택::</option>";
     $this->load->model('admin_shm');
     $user = $this->admin_shm->getDB('lio_category','ca_id',$ca_id);
     foreach($user as $d) {
      echo "<option value='{$d->ca_id}'>{$d->ca_name}</option>";
     }
     echo "</select>";
    } else if(strlen($ca_id)==12) {
     echo "
     <select name='sel5' id='sel5' onchange='sub(5)'>
     <option value=''>::최종분류 선택::</option>";
     $this->load->model('admin_shm');
     $user = $this->admin_shm->getDB('lio_category','ca_id',$ca_id);
     foreach($user as $d) {
      echo "<option value='{$d->ca_id}'>{$d->ca_name}</option>";
     }
     echo "</select>";
    } 
    exit;
    break;

모델
////////////////////////////////////////// 분류 관련 ///////////////////////////////////////////
 function ca_insert() {
  $sh_id = $this->input->post('sh_id',TRUE);
  $sql = "select ca_id from `lio_category` where ca_name='".$this->input->post('ca_name')."' order by ca_id desc limit 1";
  $query = $this->db->query($sql);
  $temp_id = $query->num_rows();
  if($temp_id>0) {
   alert_back('동일한 카테고리명이 존재 합니다.');
   return false;
  }

  $next_id = $this->Next_ca($sh_id);
  if(strlen($next_id) > 15) {
   alert_back('5단계이상은 생성할 수 없습니다.');
   return false;
  }
  $data = array(
   'ca_id' => $next_id,
   'ca_name' => $this->input->post('ca_name',TRUE),
   'weight' => $this->input->post('weight',TRUE)
   );
  $insert = $this->db->insert('lio_category', $data);
  return $insert;
 }

 // 하위 매장 또는 최상위 매장 코드 가져오기 //
 function Next_ca($parent='') {
  $length=3; $next_id = $right_pad = $left_pad= null;
  if(!$parent) {
   $sql = "select ca_id from `lio_category` where length(ca_id) = $length order by ca_id desc limit 1";
   $query = $this->db->query($sql);
      $temp_id = $query->row();
   if(!$temp_id) {
    $next_id = "101";
   }else {
    $next_id = $temp_id->ca_id + 1;
   }
  } else {
   $son_length = strlen($parent) + $length;
   $que = "select ca_id from `lio_category` where `ca_id` like '$parent%' and length(ca_id) = $son_length order by ca_id desc limit 1";
   $query = $this->db->query($que);
      $temp_id = $query->row();

   if(!$temp_id) {
    $que = "select ca_id from `lio_category` where `ca_id` like '$parent%' and length(ca_id) = $son_length  order by ca_id desc limit 1";
    $query = $this->db->query($que);
    $temp_id = $query->result();

    if(!$temp_id) {
     $next_id = $parent.'001';
    }else {
     $next_id = $temp_id->ca_id + 1;
    }
   }else {
    $right_pad = substr($temp_id->ca_id,-$length);
    $right_id = $right_pad + 1;
    for($i=strlen($right_id); $i < $length; $i++) {
     $left_pad .= '0';
    }
    $next_id = $parent.$left_pad.$right_id;
   }
  }
  return $next_id;
 }

뷰어
<strong>+ 분류 추가</strong>
<form method='post' class='form-control' name='form1' action='/admin/shop/category_ok'>
 <input type='hidden' name='sh_id' value='<?php echo $this->uri->segment(4);?>' />
 <input type='hidden' name='modify' value='<?=($this->input->get_post('id',TRUE))?'1':'0';?>' />
 <ul>
  <li><label for='ca_name' class='form_label_title'>분류명</label><input type='text'  id='ca_name' name='ca_name' size='50' value='<?php echo set_value('ca_name');?>' placeholder='' autofocus /><br />
  <span class='text-red'>분류명을 입력하세요.</span></li>
  <li><label for='ca_name' class='form_label_title'>순서</label><input type='text' id='weight' name='weight' size='4' value='<?=(isset($list->weight)&&$list->weight)?$list->weight:set_value('weight');?>' /><br /><span class='text-red'>순서를 정하고자 할 경우 숫자를 입력하세요. 낮은 순으로 정렬됩니다.</span></li>
  <li><input type='submit' class='btn btn-primary' id='submit' value='생성' /></li>
 </ul>
</form>

<div><strong>+ 분류 목록</strong></div>
<?php
 echo "<p><a href='".ADM_PATH."/shop/category'>TOP</a></p>";
 foreach($list as $ls) {
  if(strlen($ls->ca_id)=='3') {
   $space = '';
  } else if(strlen($ls->ca_id)=='6') {
   $space = '  ㄴ';
  } else if(strlen($ls->ca_id)=='9') {
   $space = '     ㄴ';
  } else if(strlen($ls->ca_id)=='12') {
   $space = '        ㄴ';
  } else if(strlen($ls->ca_id)=='15') {
   $space = '           ㄴ';
  }
  echo "<p>$space<a href='".ADM_PATH."/shop/category/".$ls->ca_id."'>".$ls->ca_name."</a></p>";
 }
?>
</div>


지금은 리스트에서 추가를 누르면 새로 생성되고 리스트 목록에서 해당 분류를 클릭하고 생성하면 그 카테고리 아래에 추가로 생성하는 구조인데 ... 이게 맞는건지 원....
참고할 만한 구글링에 소스도 그리 많지 않고.... 혼자 헤맬려니 정말 미치겠네요....
 다음글 안녕하세요. ajax input 배열일때 질문드립니다.... (3)
 이전글 파일upload시 파일사이즈 체크가 안되요 (1)

댓글

darkninja / 2014/09/25 14:31:40 / 추천 0
에 부족한 머리로 그동안 여러가지 생각을 해봤는데요
https://github.com/olimortimer/ci-nested-sets
이걸 약간 보완해서 사용하는게 나을거 같습니다.
고수정도 되면
자체 라이브러리를 구축할수 있겠지만

일단 무한 카테고리 생성이 되고
검색이 비교적 쉽습니다.
입출력이 많지 않으니 사용하는데 큰 문제는 없을거라 봅니다.
다만 익숙해지는데 시간이 많이 걸립니다.

다른 소스들도 많이 있는데
검색부분으로 들어가면
nested set 말고는 답답한거 같더군요!

이상 개인적인 의견이었습니다.
람이 / 2014/09/26 14:44:05 / 추천 0
darkninja님 답변 주셔서 감사합니다.
음 이리 복잡하게 해야 하는거 군요...
휴 ~ 카테고리는 쉬워 질 순 없는건가봐요 ㅠ.ㅜ
 
darkninja / 2014/09/26 15:06:10 / 추천 0
다른걸 사용하더라도
결국은 nested set 과 비슷한 모양이 될겁니다.
이걸 완전히 이해해서 적용한다면
아마도 sql 실력이 한단계 업그레이드 될거 같네요^^
코딩을 한다면 언젠가는 해야하는거니
이번기회에 해보세요 ㅋ