【发布时间】:2011-07-08 02:33:39
【问题描述】:
不确定最好的表达方式,请耐心等待。
在 Codeigniter 中,我可以毫无问题地返回我的对象的记录集,但这是作为 stdClass 对象而不是作为“模型”对象(例如页面对象)返回的,然后我可以使用它来使用其中的其他方法那个模型。
我在这里错过了一个技巧吗?或者这是 CI 中的标准功能?
【问题讨论】:
标签: php codeigniter codeigniter-2 models stdclass
不确定最好的表达方式,请耐心等待。
在 Codeigniter 中,我可以毫无问题地返回我的对象的记录集,但这是作为 stdClass 对象而不是作为“模型”对象(例如页面对象)返回的,然后我可以使用它来使用其中的其他方法那个模型。
我在这里错过了一个技巧吗?或者这是 CI 中的标准功能?
【问题讨论】:
标签: php codeigniter codeigniter-2 models stdclass
我对这个问题的解决方案是结合 jondavidjohn 的回答和 mkoistinen 的评论。
根据 CodeIgniter documentation:
你也可以将一个字符串传递给 result(),它代表一个类 为每个结果对象实例化(注意:必须加载此类)
有了这些知识,我们可以用这种方式重写 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
}
}
【讨论】:
你不需要这样的东西:
$this->title = $db_row->title; $this->content = $db_row->content; //Populate current instance of the Model $this->date = $db_row->date;
只要把你的模型放到result()方法中:
result(get_class($this));
或
result(get_called_class());
你会得到你的模型实例!
【讨论】:
是的,基本上为了让它工作,您需要在类范围内声明您的模型对象属性,并引用 $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。
【讨论】:
function get_entry($id) { return $this->db->where('id', $id)->get('blog_table')->row(0, "Blogmodel"); }?