【问题标题】:Codeigniter - return my model object instead of stdClass ObjectCodeigniter - 返回我的模型对象而不是 stdClass 对象
【发布时间】:2011-07-08 02:33:39
【问题描述】:

不确定最好的表达方式,请耐心等待。

在 Codeigniter 中,我可以毫无问题地返回我的对象​​的记录集,但这是作为 stdClass 对象而不是作为“模型”对象(例如页面对象)返回的,然后我可以使用它来使用其中的其他方法那个模型。

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

【问题讨论】:

    标签: php codeigniter codeigniter-2 models stdclass


    【解决方案1】:

    我对这个问题的解决方案是结合 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
        }
    }
    

    【讨论】:

      【解决方案2】:

      你不需要这样的东西:

      $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());
      

      你会得到你的模型实例!

      【讨论】:

        【解决方案3】:

        是的,基本上为了让它工作,您需要在类范围内声明您的模型对象属性,并引用 $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"); }?
        • 使用 CI,mkoistinen 的方式是正确的做法。 jondavidjohn 的方法很有效。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-29
        • 2022-01-11
        • 2017-10-06
        • 2014-10-29
        相关资源
        最近更新 更多