用户
 找回密码
 入住 CI 中国社区
搜索
查看: 6217|回复: 5
收起左侧

CI 2.02中 模型该怎么使用数据库功能呢?

[复制链接]
发表于 2011-8-17 23:42:45 | 显示全部楼层 |阅读模式
今天刚开始用个例子来测试CI2.02,就在模型的使用过程中遇到了麻烦。

模型的功能在视频教程中有讲解,一哈子是这样使用模型的

    class Mhome extends Model{
        function __construct(){
            parent::Model();
        }

但是我下载的现在的2.02版CI里,这么写好像不可以
会报错:Class 'Model' not found

这么写不报错:
    class User_model extends CI_Model{
        function __construct(){
            parent::__construct();
        }

这是按照CodeIgniter 用户指南 版本 2.0.0中对模型的要求来写的。但是这么写不能调用数据库,比如在Model中定义一个函数:
    function test(){
        $query = $this->db->get("user");
    }
当test被controller调用时:
public function log_in(){
        $this->load->model("User_model");
        $result=$this->User_model->test();
就会报错:
Call to a member function get() on a non-object

而我已经让数据库自动加载成功了,这种情况给我的感觉是在Model的子类中$this并没有和controll中同等地位的功能。所以$this->db->get()
这样的函数是不存在的。那么这个问题究竟该怎么解决了?拜托各位帮忙给看看吧!


 楼主| 发表于 2011-8-17 23:45:25 | 显示全部楼层
呃~ 发错版块了,版主给转到新手区吧
发表于 2011-8-18 08:56:02 | 显示全部楼层
class User_model extends CI_Model{
        function __construct(){
            parent::__construct();
        }
 楼主| 发表于 2011-8-18 09:41:39 | 显示全部楼层
问题解决了,怪我,没提到的是,我不应该在Model中定义了一个 变量 var $db, 造成的结果就是 $this->db代表的不是父类里的db,除了加了 $db,还加了好多其他的var,昨天从网上搜到一个解决netbeans下代码自动完成的代码段,要求加到需要实现自动完成的controller和Model类的声明中,所以我照做了,而且,在controller下很管用,没想到在Model下出现了这个问题!
发表于 2013-1-4 16:26:39 | 显示全部楼层
修改配置文件中的autoload.php文件,
Check if this is set to true in your databaseconfig file. As far as I know db->get is an active record thing, soit needs to be set to use it.
$db['default']['active_r'] = TRUE;
You can also auto load the db for each page by setting it in the autoload.php
/*
| -------------------------------------------------------------------
|  Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in the system/libraries folder
| or in your system/application/libraries folder.
|
| Prototype:
|
|    $autoload['libraries'] = array('database', 'session', 'xmlrpc');
*/

$autoload['libraries'] = array('database')
发表于 2013-1-5 00:41:26 | 显示全部楼层
{:soso_e127:}

本版积分规则