【问题标题】:Kohana 3 ORM: constructor "after load"Kohana 3 ORM:构造函数“加载后”
【发布时间】:2010-09-01 23:50:21
【问题描述】:

Kohana 3 的 ORM 中是否有任何方法可以在模型中运行一段代码,但仅在从数据库加载该模型之后?一个简单的例子是必需的 has_one 关系。

   ORM::factory('user')->where('name', '=', 'Bob')->find();

现在,如果所有用户都必须拥有一些其他属性,那么如果 Bob 不存在,就必须创建它?现在,在这条线运行的地方,我正在检查空主键,如果是,则指示模型添加该关系。但是有没有办法让模型完成呢?构造函数的问题是模型可以在从数据库填充之前构造为空的,如本示例中所示,所以我不希望那样。

【问题讨论】:

    标签: php orm kohana


    【解决方案1】:

    只需创建具有所有所需逻辑的模型方法:

    public function get_user($username)
    {
        $this->where('name', '=', $username)->find();
        if ( ! $this->_loaded)
        {
            // user not found
        }
        else
        {
            // user exists, do something else
        }
        // make it chainable to use something like this:
        //   echo ORM::factory('user')->get_user('Bob')->username;
        return $this;
    }
    

    【讨论】:

    • 扩展 find 也可以,但这种方式也可以让 find 单独处理其他事情,如果 find 方法的参数发生变化,升级会更容易一些。
    【解决方案2】:

    尝试在你的模型中重载find() 方法:

    class Model_User extends ORM {
    
        public function find($id = NULL) {
            $result = parent::find($id);
            if (!$result->loaded()) {
                // not found so do something
            }
            return $result;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-27
      相关资源
      最近更新 更多