CodeIgniter在Controller或Model中加载数据库?

时间:2016-04-27 04:57:29

标签: php database codeigniter model

型号:     

class Users_model extends CI_Model {
    function __construct() {
        parent::__construct();
        $this->load->database();
    }

    public function get_all_users() {
        return $this->db->get('users');
    }
}

控制器:     

class Users extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->helper('form');
        $this->load->helper('url');
        $this->load->helper('security');
        $this->load->model('Users_model');
    }

    public function index() {
        redirect('users/view_users');
    }

    public function view_users() {
        $data['query'] = $this->Users_model->get_all_users();
        $this->load->view('users/view_all_users', $data);
    }
}

我的问题是我应该在哪里放置$ this-> load->数据库?在模型或构造函数中?如果可能的话告诉我原因? 还有一个问题,如果我省略了$ this-> load->数据库,则会显示错误

  

“未定义的属性:Users :: $ db”。我期待“Undefined property:   Users_model :: $分贝。”

为什么?它是在控制器还是模型中寻找$ db? 谢谢。 注意:我可以很好地连接到数据库。实际上我问的是,如果我想使用$ this-> load-> database()。我应该把它放在哪里?控制器或型号?为什么?

2 个答案:

答案 0 :(得分:1)

转到autoload.php中的application/config/autoload.php并添加此

$autoload['libraries'] = array('database'); // add database in array(now you dont need to load database at anywhere in project)

database.php,位于application/config/database.php

的文件中进行数据库连接设置

现在试试这个

 class Users_model extends CI_Model {
  function __construct() {
    parent::__construct();
    //$this->load->database(); <----remove this
  }

  public function get_all_users() {
    return $this->db->get('users');
  }
}

答案 1 :(得分:1)

您可以在控制器中加载数据库,也可以将其加载到模型中。

由于数据库中的所有交互都处于简洁状态,因此它没有太大区别。模型和控制器是连接视图和模型的人。

这里的控制器就像买卖双方之间的中间人。

在控制器中加载数据库

<?php 
   class Test_controller extends CI_Controller {

        public function __construct()
      {
          parent::__construct();
          $this->load->database('default');
          $this->load->model('test_model');
      }

      public function index()
      {
        $this->db->from('test');
        $query = $this->db->get();
        echo "<title>CodeIgniter SQlite</title>";
        $data['db']=$query->result();
        //print_r($data['db']);
        $count = count($data['db']);
        echo "Row count: $count rows<br>";
        for ($i=0; $i < $count; $i++) { 
          echo $data['db'][$i]->text." ";
        }
      }
   }
?>

在模型中加载数据库

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Test_model extends CI_Model
{

    public $table1 = 'test';
    public $table2 = '';



    public function __construct()
    {
        parent::__construct();
        $this->load->database('default');
    }

    public function check_db()
    {
        $this->db->from($this->table1);
        $query = $this->db->get();
        return $query->result();
    }
}