【问题标题】:$db undefined when using model from helper in codeigniter在 codeigniter 中使用 helper 中的模型时 $db 未定义
【发布时间】:2011-09-15 19:26:04
【问题描述】:

我想要一个简单的助手,在我的数据库中记录一次命中。我创建了一个 $CI 实例并尝试像这样访问模型...

$CI->load->model('stats_model');
$CI->stats_model->set_hit();

但我在模型中遇到错误..

Severity: Notice
Message: Undefined property: Stats_model::$db
Filename: models/stats_model.php
Line Number: 16

第 16 行是一个简单的...

$this->db->select('*');

我从这个链接http://blog.avinash.com.np/2010/07/01/talk-to-the-database-from-a-helper-codeigniter/得到了这样做的想法

我在模型中尝试了 $CI->db... 而不是 $this->db 但仍然没有运气,有什么想法吗?

帮手

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

function check_hit() {
//stuff that uses CI
$CI = & get_instance();
$CI->load->library('user_agent');
if ($CI->agent->is_robot()) {
    return FALSE;
} else {

    //check for a 12 hour cookie
    $check = $CI->input->cookie('stat');

    if ($check == false) {
        //insert a database entry
        $CI->load->model('Stats_model');
        $CI->Stats_model->set_hit();

        //set a cookie

        $cookie = array(
            'name' => 'stat',
            'value' => '1',
            'expire' => '43200'
        );

       // $CI->input->set_cookie($cookie);
    }
}
}

check_hit();
?>

型号

<?php

if (!defined('BASEPATH'))
exit('No direct script access allowed');

class Stats_model extends Model {

function Stats_model() {
// Call the Model constructor
    parent::Model();
}

function set_hit() {
    $date = date('Y-m-d');

    $this->db->select('unique_visitors');
    $this->db->from('daily_stats');
    $this->db->where('date', $date);
    $query = $this->db->get();
    $date_rows = $query->num_rows();
    $result = $query->row();
    $visits = $result->unique_visitors;
    $visits++;

    $data = array(
        'unique_visitors' => $visits,
        'date' => $date
    );

    if ($date_rows == 1) {
        $this->db->where('date', $date);
        $this->db->update('daily_stats', $data);
    } else {
        $this->db->insert('daily_stats', $data);
    }
}

}
?> 

【问题讨论】:

  • 这听起来可能很愚蠢,但您正在加载数据库驱动程序,对吧?
  • 它被加载到自动加载配置文件中。如果我尝试使用 ... $CI->load->library('database'); 在帮助程序中再次加载它我收到一个错误...无法加载请求的类:数据库
  • 不,如果它在自动加载中,应该没问题。我只是想检查一下。
  • 感谢所有回答我问题的人。我从来没有找到答案,但我认为这是因祸得福,因为现在我使用 Gapi(谷歌分析 php api)作为助手,并在 cron 作业中获取每日统计信息。更清洁的解决方案!

标签: codeigniter model helper


【解决方案1】:

前段时间这部分让我有点困惑。这似乎奏效了。


//load the CI instance
$this->ci =& get_instance();


//run a db get
$this->ci->db->get('mytable');

【讨论】:

  • 感谢您的回复,但它仍然不适合我。我试过把 $this->ci =& get_instance();在模型函数中,但我得到了同样的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-18
  • 2018-11-17
  • 2012-02-14
  • 1970-01-01
  • 1970-01-01
  • 2017-06-07
相关资源
最近更新 更多