yii的一些方法的解析和blog的详细解析(一)

转载自:http://www.yiichina.org/forum/thread-218-1-1.html

这里提供一些yii的方法解析,希望能够对新手有一点帮助:

1.  存取数据库方法
存储第一种(SAVE )
   存表时候用到  
   例子:

  1. $post=new Post;
  2.    $post->title='sample post';
  3.    $post->content='content for the sample post';
  4.    $post->createTime=time();/$post->createTime=new CDbexpression_r('NOW()');
  5.    $post->save();   
  6.   $user_field_data= new user_field_data;
  7.   $user_field_data->flag=0;
  8.   $user_field_data->user_id=$profile->id;
  9.   $user_field_data->field_id=$_POST['emailhiden'];
  10.   $user_field_data->value1=$_POST['email'];
  11.   $user_field_data->save();   //注:当一个表存储4次的时候,需要创建4个handle new4次
复制代码

存储第二种(存储)   
    存储后我们需要找到这条记录的流水id 这样做 $profile = new profile; $profile->id;
   

   存储第三种 用于更加安全的方法,来绑定变量类型  这样可以在同一个表中存储两个记录

  1.    $sql="insert into user_field_data(user_id,field_id,flag,value1) values(:user_id,:field_id,:flag,:value1);";
  2.      $command=user_field_data::model()->dbConnection->createCommand($sql);
  3.      $command->bindParam(":user_id",$profile->id,PDO::PARAM_INT);
  4.      $command->bindParam(":field_id",$_POST['firstnamehiden'],PDO::PARAM_INT);
  5.      $command->bindParam(":flag",$tmpflag,PDO::PARAM_INT);
  6.      $command->bindParam(":value1",$_POST['firstname'],PDO::PARAM_STR);
  7.      $command->execute();
  8.      $command->bindParam(":user_id",$profile->id,PDO::PARAM_INT);
  9.      $command->bindParam(":field_id",$_POST['emailhiden'],PDO::PARAM_INT);
  10.      $command->bindParam(":flag",$tmpflag,PDO::PARAM_INT);
  11.      $command->bindParam(":value1",$_POST['email'],PDO::PARAM_STR);
  12.      $rowchange = $command->execute();
  13.      // 用来判断
  14.      if( $rowchange != 0){  修改成功 }
复制代码

注:update delete都可以用这个方法

  1. $sql="delete from profile where id=:id";
  2.      $command=profile::model()->dbConnection->createCommand($sql);
  3.      $command->bindParam(":id",$userid,PDO::PARAM_INT);
  4.      $this->rowflag=$command->execute();
  5.     
  6.      $sql="update profile set pass=:pass,role=:role where id=:id";
  7.      $command=profile::model()->dbConnection->createCommand($sql);
  8.      $command->bindParam(":pass",$password,PDO::PARAM_STR);
  9.      $command->bindParam(":role",$role,PDO::PARAM_INT);
  10.      $command->bindParam(":id",$userid,PDO::PARAM_INT);
  11.      $this->rowflag=$command->execute();     // 同理变更updateAll()模式
  12.      $sql="update user_field_data set flag = :flag where user_id= :user_id and field_id= :field_id ";
复制代码

//原始sql语句

  1. $criteria = new CDbCriteria;
  2.      $criteria->condition = 'user_id = :user_id and field_id= :field_id';
  3.      $criteria->params = array(':user_id' => $userid,':field_id' => $fieldid);
  4.      $arrupdate = array('flag' => $flag);
  5.      if(user_field_data::model()->updateAll($arrupdate,$criteria) != 0)
  6.         {
  7.            //更新成功后。。。
  8.          }
复制代码

第四种更新和存储应用同一个handle 流程:先查询记录是否存在,若存在就更新,不存在就新创建
     
      注:1.第一次查询的变量,要跟save()前的变量一致。
              2.存储时候需要再次 new一下库对象      $user_field_data = user_field_data::model()->findByAttributes(

  1. $attributes = array('user_id' => Yii::app()->user->user_id, 'field_id' => $key));
  2.                 if ($user_field_data !== null)
  3.                    {
  4.                       $user_field_data->value1 = $value;
  5.                       $user_field_data->save();
  6.                   }
  7.                  else
  8.                     {
  9.                         $user_field_data = new user_field_data;
  10.                         $user_field_data->user_id = Yii::app()->user->user_id;
  11.                         $user_field_data->field_id = $key;
  12.                         $user_field_data->value1 = $value;
  13.                         $user_field_data->save();
  14.                     }
复制代码

2、查询数据
   注:当项目没查找到整个对象会为空需要这样判定
       if($rows !== null) 当对象不为空
           {
                 return true;
           }else{
                 return false;
           } 
      
   
   SELECT
   读表时候用到
  第一种find()

  1. // find the first row satisfying the specified condition
  2.    $post=Post::model()->find($condition,$params);
  3.    // find the row with postID=10
  4.    $post=Post::model()->find('postID=:postID', array(':postID'=>10));   同样的语句,用另种方式表示
  5.    $criteria=new CDbCriteria;
  6.    $criteria->select='title';  // only select the 'title' column
  7.    $criteria->condition='postID=:postID';
  8.    $criteria->params=array(':postID'=>10);
  9.    $post=Post::model()->find($criteria); // $params is not needed   第二种 find()
  10.    $post=Post::model()->find(array(
  11.        'select'=>'title',
  12.        'condition'=>'postID=:postID',
  13.        'params'=>array(':postID'=>10),
  14.    ));   // find the row with the specified primary key
  15.    $post=Post::model()->findByPk($postID,$condition,$params);
  16.       
  17.    // find the row with the specified attribute values
  18.    $post=Post::model()->findByAttributes($attributes,$condition,$params);
复制代码

示例:第一种 findByAttributes()

  1. $checkuser = user_field_data::model()->findByAttributes(
  2.    array('user_id' => Yii::app()->user->user_id, 'field_id' => $fieldid));
复制代码

第二种 findByAttributes()

  1. $checkuser = user_field_data::model()->findByAttributes(
  2.    $attributes = array('user_id' => Yii::app()->user->user_id, 'field_id' => $fieldid));
复制代码

第三种 当没有conditions时候,不用params

  1. $user_field_data = user_field_data::model()->findAllByAttributes(
  2.    $attributes = array('user_id' => ':user_id'),
  3.    $condition = "field_id in (:fields)",
  4.    $params = array(':user_id' => Yii::app()->user->user_id, ':fields' => "$rule->dep_fields"));
  5.    
  6.    // find the first row using the specified SQL statement
  7.    $post=Post::model()->findBySql($sql,$params);
复制代码

例子
   user_field_data::model()->findBySql("select id from user_field_data where user_id = :user_id and field_id = :field_id ", array(':user_id' => $userid,':field_id'=>$fieldid));
   此时回传的是一个对象
     
   第四种  添加其他条件 
      http://www.yiiframework.com/doc/api/CDbCriteria#limit-detail

  1.   $criteria = new CDbCriteria;
  2.       $criteria->select ='newtime';  //选择只显示哪几个字段要与库中名字相同,但是不能COUNT(newtime) as name这样写
  3.       $criteria->join = 'LEFT JOIN Post ON Post.id=Date.id';
复制代码

1. 先要在relation函数中增加与Post表的关系语句 
    
       2. Date::model()->with('post')->findAll($criteria)
       $criteria->group  = 'newtime';
       $criteria->limit  = 2; // 都是从0开始,选取几个
       $criteria-> offset = 2;// 从哪个偏移量开始
       print_r(Date::model()->findAll($criteria));
   
   得到行数目或者其他数目 count

  1. // get the number of rows satisfying the specified condition
  2.    $n=Post::model()->count($condition,$params);
  3.    // get the number of rows using the specified SQL statement
  4.    $n=Post::model()->countBySql($sql,$params);
  5.    // check if there is at least a row satisfying the specified condition
  6.    $exists=Post::model()->exists($condition,$params);
复制代码

3、更新(UPDATE)
   例子:

  1. $post=Post::model()->findByPk(10);
  2.    $post->title='new post title';
  3.    $post->save(); // save the change to database
  4.    
  5.    // update the rows matching the specified condition
  6.    Post::model()->updateAll($attributes,$condition,$params);   例子:或者参考上面例子
  7.    $c=new CDbCriteria;
  8.    $c->condition='something=1';
  9.    $c->limit=10;  
  10.    $a=array('name'=>'NewName');  
  11.    Post::model()->updateAll($a, $c);
  12.    
  13.    // update the rows matching the specified condition and primary key(s)
  14.    Post::model()->updateByPk($pk,$attributes,$condition,$params);   例子
  15.    $profile = profile::model()->updateByPk(
  16.    Yii::app()->user->user_id,
  17.    $attributes = array('pass' => md5($_POST['password']), 'role' => 1));
  18.     
  19.    // update counter columns in the rows satisfying the specified conditions
  20.    Post::model()->updateCounters($counters,$condition,$params);
  21.    
复制代码

4、删除(DELETE)
   例子:

  1. $post=Post::model()->findByPk(10); // assuming there is a post whose ID is 10
  2.    $post->delete(); // delete the row from the database table
  3.    // delete the rows matching the specified condition
  4.    Post::model()->deleteAll($condition,$params);
  5.    // delete the rows matching the specified condition and primary key(s)
  6.    Post::model()->deleteByPk($pk,$condition,$params);
复制代码

5、比较(COMPARE)
  目前可以取出的

  1. 1.  $allquestion=field::model()->findAllBySql("select label from field where step_id = :time1 ", array(':time1' =>1));
  2.    
  3.    2. 
  4.       $criteria=new CDbCriteria;
  5.       $criteria->select='label,options';
  6.       $criteria->condition='step_id=:postID';
  7.       $criteria->params=array(':postID'=>1);
  8.       $allquestion=field::model()->findAll($criteria);
  9.      $allquestion=field::model()->find("",array("label"));
复制代码

可以与在models文件夹中的 库连接文件relations()函数合用,这样可以联合查询

  1. $criteria=new CDbCriteria;
  2.     $criteria->condition='field.step_id=1';
  3.     $this->_post=field::model()->with('step')->findAll($criteria);
复制代码

这样出来的数组里面包含step表中的值,且这个值的条件为 step.id=field.step_id

  1.   public function relations()
  2.         {
  3.                   return array(
  4.                                             'step'=>array(self::BELONGS_TO, 'step', 'step_id'),
  5.                                        );
  6.        }
复制代码
posted on 2011-04-28 18:58  DavidYanXW  阅读(2033)  评论(0)    收藏  举报