php-activerecord例外

时间:2011-11-01 21:17:55

标签: php codeigniter activerecord

我似乎无法找到使用METHOD捕获ActiveRecord Exceptions的方法:2

方法:1这可以按预期工作,足够了解记录错误的对象!

$model = model::find(id);
if($model->delete()){
echo 'yay';
}else{
throw new \ActiveRecord\ActiveRecordException($model->errors())
}

// METHOD:2这没有记录错误的信息

if(Model::create(attributes)){
echo 'yay'
}else{
throw new \ActiveRecord\ActiveRecordException('where do I pull error from now?')
}

//我的真实世界的例子

public function create(){

    //grab the validation data from $this->validation_rules
    $this->form_validation->CI = & $this;
    $this->form_validation->set_rules($this->validation_rules);

    //run the validation
    if ($this->form_validation->run($this)) {

        //loop through $_POST data and change any $key[values] where needed
         foreach($this->input->post() as $k => $v){
             if($k == 'status'){
                 $v = ($v === 'publish') ? 1 : 0;

             }
             // recomplie $_POST with modified values into temp array and break out of loop
              $tmp[$k] = $v;
             continue;
         }

        //try to create a new page ( throw exception : build )  
        try{
            if(!Page::create($tmp)){
                throw new \ActiveRecord\ActiveRecordException('Arrrgh custom error required with some guess work?');
            }else{
                $this->session->set_flashdata('success', 'Page Successfully Created');
                redirect('admin/pages');
            }
        }catch(\ActiveRecord\ActiveRecordException $e){
            //log any errors thrown 
            log_message('error', $e->getMessage());
        }
        // validation failed, show form again
    }else{
        $this->create_form();
    }
}

1 个答案:

答案 0 :(得分:2)

是否有理由使用Model::create()

如果您使用

,我认为您的问题不存在
$model = new Model($attributes);