(转载)数据库读写方法:AR模型的方法重载和事务

一、AR模型方法

  AR模型是ORM方式的一种,其将SQL查询进行封装,使得数据库读写更加方便便捷。其中一个AR类代表数据库中的一张表。

  1.类的定义(Model模型)

    定义方式如下:

    class Post extends CActiveRecord
    {
      public static function model($className=__CLASS__)
      {
        return parent::model($className);
      }
      publicfunction tableName()
      {
        return 'tbl_post';
      }
    }

  这是一个Model类的最小代码。

  2.函数重载

    在执行记录的时候可以伴随着函数调用,

    这些函数主要 有:beforeValidate, afterValidate, beforeSave, afterSave, beforeDelete, afterDelete, afterConstruct, beforeFind, afterFind

  3.使用事务

    事务可以将读写操作作为一个整体进行,有效防止数据库读写出错。

     $model=Post::model();

    $transaction=$model->dbConnection->beginTransaction();
    try
    {
      // find and save are two steps which may be intervened by another request
      // we therefore use a transaction to ensure consistency and integrity
      $post=$model->findByPk(10);
      $post->title='new post title';
      $post->save();
      $transaction->commit();
    }
    catch(Exception$e)
    {
      $transaction->rollback();
    }
 
转载于 :http://janson.blog.51cto.com/5323740/1286915
posted @ 2014-04-08 17:44  zone人  阅读(199)  评论(0)    收藏  举报