Codeigniter - 返回我的模型对象而不是stdClass对象

sim*_*nom 5 php codeigniter stdclass models codeigniter-2

不确定这句话的最佳方法是如何忍受我.

在Codeigniter中,我可以返回我的对象​​的记录集没有问题,但是它作为stdClass对象而不是作为"模型"对象(例如页面对象)返回,然后我可以使用该对象来使用该模型中的其他方法.

我在这里错过了一招吗?或者这是CI中的标准功能吗?

jon*_*ohn 8

是的,基本上为了使其工作,您需要在类范围内声明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
    }
}
Run Code Online (Sandbox Code Playgroud)

我相信get_entry()会返回一个对象类型Blogmodel.

  • 真正的问题在这里,为什么不这样做:`function get_entry($ id){return $ this-> db-> where('id',$ id) - > get('blog_table') - > row(0," Blogmodel"); }`? (3认同)