在控制器中运行数据库功能..如何转移到模型?

时间:2012-11-08 19:33:40

标签: php codeigniter

好的,我的控制器中有一个功能正常。但是,我不应该在控制器中调用数据库(我们都知道)。我通常可以轻松地将信息从模型迁移到控制器中,但是我很难用这个。我甚至不会分享我的模型版本......你会怎么写这个模型?

    $this -> db -> select('title, price, number_sites, number_entries, white_label'); 
    $query = $this -> db -> get('pricing', 3); // limit 3 rows

    $row1 = $query->row(0); // 0 grabs first row in table: Package 1        
    $data['row1'] = $row1;

    $row2 = $query->row(1); // 1 grabs second row in table: Package 2        
    $data['row2'] = $row2;

    $row3 = $query->row(2); // 2 grabs third row in table: Package 3        
    $data['row3'] = $row3;

2 个答案:

答案 0 :(得分:2)

只需将其复制并粘贴到您要调用的函数中的模型中:

function dbstuff(){
    $this -> db -> select('title, price, number_sites, number_entries, white_label'); 
    $query = $this -> db -> get('pricing', 3); // limit 3 rows

    $row1 = $query->row(0); // 0 grabs first row in table: Package 1        
    $data['row1'] = $row1;

    $row2 = $query->row(1); // 1 grabs second row in table: Package 2        
    $data['row2'] = $row2;

    $row3 = $query->row(2); // 2 grabs third row in table: Package 3        
    $data['row3'] = $row3;
    return $data;
}

然后在你的控制器中:

$this->load->model('MyModel');
$data=$this->MyModel->dbstuff();
$this->load->view('view',$data);

答案 1 :(得分:0)

我建议你创建一个模型类,它包含一个静态方法,用于包装查询以从数据库中选择并返回模型类的实例。

例如:

class MyModelClass {

// Your class code here

static function findByPricing($price){

    $output = array();

   //run your query here using your db handler

   foreach($resultingrows as $row){

       $object = new MyModelClass();
       $object->setAttributeOne($row['attribute_one');
       $object->setAttributeTwo($row['attribute_two');
       $object->setAttributeThree($row['attribute_three');

       $output[] = $object;

   }

   return $output;

}


}

然后从你的控制器那里做:

 $objects = MyModelClass::findByPricing(3);