【问题标题】:Database Queries without Model Objects on CodeIgniterCodeIgniter 上没有模型对象的数据库查询
【发布时间】:2017-05-19 23:40:57
【问题描述】:

我真的可以在不创建模型的新实例的情况下进行数据库查询吗?

例如,在我的控制器中,我有 (CONTROLLER)

Name_Model::get_all_from_another_table();

并以我的名字_model.php (MODEL)

public static function get_all_from_another_table() {
    $this->db->query('select * from another_table');
    return $x;
}

在创建新模型实例之前加载具有预定义值的表会发生这种情况。

以上代码返回:

Fatal error: Using $this when not in object context

【问题讨论】:

  • 你为什么不试试$this->load->model('name_model')?在控制器上执行此操作。我们应该使用$this->name_model->get_all_from_another_table() 来调用它。
  • @Ukasyah Fatal error: Using $this when not in object context 。发生同样的错误。
  • 我认为我们在函数上使用“静态”时不能使用 $this

标签: php mysql database codeigniter


【解决方案1】:

先试试吧。

控制器:

 $this->load->model( 'name_model' );
 $data = $this->name_model->get_all_from_another_table()->result();
 print_r( $data ); //just for testing...

型号:

//Model name: name_model.php

public static function get_all_from_another_table() {
    $this->db->query('select * from another_table');
    return $x;
}

【讨论】:

    【解决方案2】:

    控制器:

    // Model File and Class Name first Character Must be Uppercase
    
    $this->load->model( 'Name_model' ); 
    $data = $this->Name_model->get_all_from_another_table();
    print_r($data); //You result is print here
    

    型号:

    //Model name: Name_model.php
    
    public static function get_all_from_another_table() {
        $query = $this->db->query('select * from another_table');
        return $query->result();
    }
    

    【讨论】:

    • 我不这么认为,在 CI 3 中加载时可以使用小写字母。相信我,它有效。
    • 好吧,也许它正在起作用,但有时它会受到影响,所以我们必须养成这个对我们有好处的好习惯。
    猜你喜欢
    • 2012-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    相关资源
    最近更新 更多