不知道这个措辞的最佳方式,以便和我一起承担。笨 - 返回,而不是stdClass的对象我的模型对象
在Codeigniter中,我可以返回一个我的对象的记录集没有问题,但这是作为stdClass对象而不是作为“模型”对象(例如Page对象)返回的,然后我可以使用其他方法在该模型中。
我在这里错过了一招吗?或者这是CI内的标准功能?
不知道这个措辞的最佳方式,以便和我一起承担。笨 - 返回,而不是stdClass的对象我的模型对象
在Codeigniter中,我可以返回一个我的对象的记录集没有问题,但这是作为stdClass对象而不是作为“模型”对象(例如Page对象)返回的,然后我可以使用其他方法在该模型中。
我在这里错过了一招吗?或者这是CI内的标准功能?
是的,基本上是为了这个工作,你需要声明你的模型对象属性的类范围,并参考$this
为当前模型对象。
class Blogmodel extends CI_Model {
var $title = '';
var $content = ''; // Declare Class wide Model properties
var $date = '';
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_entry()
{
$query = $this->db->query('query to get single object');
$db_row = $query->row(); //Get single record
$this->title = $db_row->title;
$this->content = $db_row->content; //Populate current instance of the Model
$this->date = $db_row->date;
return $this; //Return the Model instance
}
}
相信get_entry()
会返回一个对象类型Blogmodel
。
你并不需要某事像:
$this->title = $db_row->title; $this->content = $db_row->content; //Populate current instance of the Model $this->date = $db_row->date;
只要把该结果()方法UR模式:
result(get_class($this));
或
result(get_called_class());
而且你会得到你的模型的实例!
我对这个问题的解决方案包括jondavidjohn答案,并mkoistinen的评论相结合的。
按照笨documentation:
你也可以传递一个字符串,导致(),它代表了一类以 实例化每个结果对象(注:这个类必须被加载)
武装与知识,我们可以重写jondavidjohn的解决方案是这样的:
class Blogmodel extends CI_Model {
var $title = '';
var $content = ''; // Declare Class wide Model properties
var $date = '';
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_entry()
{
$query = $this->db->query('query to get single object');
$blogModel = $query->row('Blogmodel'); //Get single record
return $blogModel; //Return the Model instance
}
}
优秀的感谢 - T的帽子完美地为我澄清了它。 – simnom 2011-03-04 11:18:03
真正的问题在这里,为什么不只是这样做: '函数get_entry($ ID){$返回这 - > DB->在哪里( '身份证',$ ID) - >获取( 'blog_table') - >行( 0,“Blogmodel”); }'? – mkoistinen 2012-12-18 01:59:52
与CI,mkoistinen的办法是做正确的方式。 jondavidjohn的方式虽然工作。 – twnaing 2013-01-09 08:33:17