如何在模型中运行查询并加载控制器?

时间:2013-09-25 13:52:38

标签: php mysql codeigniter

我正在控制器中进行查询,但我注意到我应该在模型中进行查询。

这是我在控制器中的代码

    $this->db->where('page', 'your-secret-skill');
    $this->data['articles'] = $this->article_m->get();

这是我在核心模型中的get方法:

    public function get($id = NULL, $single = FALSE){

    if ($id != NULL) {
        $filter = $this->_primary_filter;
        $id = $filter($id);
        $this->db->where($this->_primary_key, $id);
        $method = 'row';
    }
    elseif($single == TRUE) {
        $method = 'row';
    }
    else {
        $method = 'result';
    }

    if (!count($this->db->ar_orderby)) {
        $this->db->order_by($this->_order_by);
    }
    return $this->db->get($this->_table_name)->$method();
}

我如何解决这个问题并在文章模型中进行查询并将其加载到控制器中?

2 个答案:

答案 0 :(得分:1)

您应该使用Articles模型继承CI_Model,并且在其中您可以将查询编写为:

class Articles_m extends CI_Model
{
    function __construct()
    {
          parent::__construct();
          $this->table_name = 'articles';
     }


    public function get()
    {
     $this->db->where('page', 'your-secret-skill');
     $query = $this->db->get($this->table_name);
     return $query->result();
    }

}

然后在你的控制器中:

$this->data['articles'] = $this->article_m->get();

答案 1 :(得分:0)

首先从控制器中删除此行:

$this->db->where('page', 'your-secret-skill');

而是将your-secret-skill作为参数发送到模型函数:

$where = array( 'page', 'your-secret-skill' );
$this->data['articles'] = $this->article_m->get('','',$where);

在你的模特中:

public function get($id = NULL, $single = FALSE, $where = array){
    if(isset($where) && is_array($where)){
        $this->db->where($where);
    }
}
相关问题