2017-12-10 1 views
0

제품 클래스는 제품 ID 또는 제품 번호를 통해 얻을 수 있습니다. 그래서 저는 2 명의 생성자를 생성했습니다. 클래스는 데이터베이스를 통해 제품을 검색하고 결과를 클래스 변수에 매핑합니다.Acces within class

class Partnumber extends CI_Model 
{ 
    private $partNr; 
    private $description; 
    private $type; 

    public function __construct() { 
    } 

    public static function withId($id) { 
     $instance = new self(); 
     $instance->loadByID($id); 
     return $instance; 
    } 

    public static function withNr($partnumber) { 
     $instance = new self(); 
     $instance->getIdFromPartnumber($partnumber); 
     return $instance; 
    } 

    protected function loadByID($id) { 
     $instance = new self(); 
     $instance->getPartnumberFromId($id); 
     return $instance; 
    } 

    private function getIdFromPartnumber($partnumber){ 
     $this->db->select("*"); 
     $this->db->from('part_list'); 
     $this->db->where('part_number', $partnumber); 
     $query = $this->db->get(); 

     return $query->result_object(); 
    } 

    //get the partnumber from an part id 
    private function getPartnumberFromId($partId){ 
     $this->db->select("*"); 
     $this->db->from('part_list'); 
     $this->db->where('id', $partId); 
     $query = $this->db->get(); 

     $this->mapToObject($query->result()); 
    } 

    private function mapToObject($result){ 
     $this->partNr = $result[0]->Part_number; 
     $this->description = $result[0]->Description; 
     $this->type = $result[0]->Type; 
    } 

    public function toJson(){ 
     return json_encode($this->partNr); 
    } 
} 

매핑이 작동합니다 (오류를 발견해야 함). 하지만 toJson 메서드를 호출 할 때 모든 값은 null입니다.

나는 다음과 같이 호출 :

class TestController extends MX_Controller{ 
    public function __construct(){ 
     parent::__construct(); 
     $this->load->model('Partnumber'); 
    } 

    public function loadPage() { 
      $p = Partnumber::withId(1); 
      echo $p->toJson(); 

    } 

} 

그리고 그래, 내가 매핑 방법에있는 모든 항목을 인쇄 할 수 있기 때문에 데이터가 돌아 오는 것을 확실히 알고있다. 그러나 toJson을 통해 데이터에 액세스하면 데이터가 왜 사라지나요?

답변

1

withIdloadByID은 모델의 새 인스턴스를 만듭니다. 에서 생성 된 모델에 데이터를로드하지 않습니다.

+1

으음, 알겠습니다. 감사! – da1lbi3