[英]Codeigniter - return my model object instead of stdClass Object
不確定這句話的最佳方法是如何忍受我。
在Codeigniter中,我可以返回我的對象的記錄集沒有問題,但是它作為stdClass對象而不是作為“模型”對象(例如頁面對象)返回,然后我可以使用該對象來使用該模型中的其他方法。
我在這里錯過了一招嗎? 或者這是CI中的標准功能嗎?
是的,基本上為了使其工作,您需要在類范圍內聲明您的Model對象屬性,並引用$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的評論。
根據CodeIgniter 文檔 :
您還可以將一個字符串傳遞給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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.