注:当项目没查找到整个对象会为空需要这样判定
if($rows !== null) 当对象不为空 { return true; }else{ return false; }
SELECT,读表时候用到
find()
第一种find()
// find the first row satisfying the specified condition $post=Post::model()->find($condition,$params); // find the row with postID=10 $post=Post::model()->find('postID=:postID', array(':postID'=>10));
同样的语句,用另种方式表示
$criteria=new CDbCriteria; $criteria->select='title'; // only select the 'title' column $criteria->condition='postID=:postID'; $criteria->params=array(':postID'=>10); $post=Post::model()->find($criteria); // $params is not needed
第二种find()
$post=Post::model()->find(array( 'select'=>'title', 'condition'=>'postID=:postID', 'params'=>array(':postID'=>10), )); // find the row with the specified primary key $post=Post::model()->findByPk($postID,$condition,$params);
findByAttributes()
$post=Post::model()->findByAttributes($attributes,$condition,$params);
第一种findByAttributes()
$checkuser = user_field_data::model()->findByAttributes( array('user_id' => Yii::app()->user->user_id, 'field_id' => $fieldid));
第二种findByAttributes()
$checkuser = user_field_data::model()->findByAttributes( $attributes = array('user_id' => Yii::app()->user->user_id, 'field_id' => $fieldid));
第三种当没有conditions时候,不用params
$user_field_data = user_field_data::model()->findAllByAttributes( $attributes = array('user_id' => ':user_id'), $condition = "field_id in (:fields)", $params = array(':user_id' => Yii::app()->user->user_id, ':fields' => "$rule->dep_fields"));
// find the first row using the specified SQL statement
$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
$criteria = new CDbCriteria; $criteria->select ='newtime';//选择只显示哪几个字段要与库中名字相同,但是不能COUNT(newtime) as name这样写 $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 // get the number of rows satisfying the specified condition $n=Post::model()->count($condition,$params); // get the number of rows using the specified SQL statement $n=Post::model()->countBySql($sql,$params); // check if there is at least a row satisfying the specified condition $exists=Post::model()->exists($condition,$params);
近期评论