• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I use database in expend core Model class?

#1
[eluser]kirrie[/eluser]
application/libraries/MY_Model.php
Code:
class MY_Model extends Model{

     var $model = "";

     function MY_Model(){
          parent::Model();
     }

     function foo(){
          return $this->db->get($this->model);
     }

}

application/models/User_Model.php
Code:
class User_Model extends MY_Model{

     var $model = "users";

     function User_Model(){
          parent::MY_Model();
     }

}

application/controllers/User.php
Code:
class User extends Controller{

     function User(){
          parent::Controller();
     }

     function index(){
          $this->load->model("user_model", "user");
          $this->user->foo();
     }

}

What I expect:
1. When user controller runs index() method, controller loads user model.
2. When user_model is loading, it extends MY_Model.
3. And MY_Model extends Model automatically.
4. Therefore I can get result records from "users" table.

What problem is:
1, 2, 3 look like ok.
When CI tries to execute 4, it says like:
Code:
A PHP Error was encountered

Severity: Notice

Message: Undefined property: User_Model::$db

Filename: libraries/MY_Model.php

Line Number: 42

Fatal error: Call to a member function get() on a non-object in F:\xampplite\htdocs\forum\system\application\libraries\MY_Model.php on line 42

I think there is no database instance. But why? MY_Model extended Model exactly. :-?

Temporarily, I added some codes for loading database.
Code:
class MY_Model extends Model{

     var $model = "";

     function MY_Model(){
          parent::Model();

          //loading database;
          $CI =& get_instance();
          $CI->load->database();
          $this->db =& $CI->db;
     }

     function foo(){
          return $this->db->get($this->model);
     }

}

How can I use database instance($this->db) in this expend core Model class without adding codes for loading database?

(Sorry for my poor english.)

#2
[eluser]Unknown[/eluser]
Anyone knows? :/

#3
[eluser]crumpet[/eluser]
i don't think you can extend the model class
something i noticed though is you need to pass TRUE as a third paramter to $this->load->model()
otherwise the database will not connect

#4
[eluser]Johan André[/eluser]
Quote:I think there is no database instance. But why? MY_Model extended Model exactly. :-?

Database core class is not loaded by default.


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme ¬© 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.