我有一个具有所有常见数据库功能的模型,例如:
class MY_Model extends CI_Model {
public $table;
function __construct()
{
parent::__construct();
$this->load->database();
}
function insert($data) {
$this->db->insert($this->table,$data);
return $this->db->insert_id();
}
function update($where=array(),$data) {
$this->db->update($this->table,$data,$where);
return $this->db->affected_rows();
}
function delete($where=array()) {
$this->db->delete($this->table,$where);
return $this->db->affected_rows();
}
//ETC.
}
现在,我有一个扩展它的模型,所以在构造函数中我定义了我应该使用的表,例如:
class other_model extends MY_Model {
function __construct()
{
parent::__construct();
$this->load->database();
$this->table = 'MY_TABLE';
}
}
在控制器中我会这样做:
$this->load->model('other_model');
$id_affected = $this->other_model->insert(...);
现在我想利用这段代码并重用它,所以我想让表名变量并从控制器传递给这样的模型:
$this->load->model('other_model');
$table_name = 'TABLE_1'
$this->other_model->set_variable($table_name);
$id_affected = $this->other_model->insert(...);
有没有办法做到这一点?我在尝试:
模型:
class other_model extends MY_Model {
var $variable;
function __construct() {
parent::__construct();
//tried here
//$this->load->database();
//$this->table = $variable;
}
function set_variable($variable) {
$this->variable = $variable;
//also tried here
//$this->load->database();
//$this->table = $variable;
}
}
控制器:
class test extends CI_Controller {
function tester() {
$this->load->model('other_model');
$variable = 'MY_TABLE_1'
$this->other_model->set_variable($variable);
}
}