Yii AR很好很强大,但刚开始不知道怎么使用
如果英文不错,可以直接看原文地址http://www.yiiframework.com/doc/guide/1.1/en/database.ar
对于一个Model Post 有如下的4中查询方法,返回对象或者对象数组。
// find the first row satisfying the specified condition
// find the row with the specified primary key
$post=Post::model()->findByPk($postID,$condition,$params);
// find the row with the specified attribute values
$post=Post::model()->findByAttributes($attributes,$condition,$params);
// find the first row using the specified SQL statement
$post=Post::model()->findBySql($sql,$params);
假设我们查询postID = 10的数据,怎么查询呢,见下面
// find the row with postID=10
条件$condition 就是我们sql里的where部分,那参数怎么办呢,通过params传递,不过名字是加了":"的。
YII有个CDbCriteria类来构造查询,如果我们查询postId为10的title,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
你也可以写成下面这样
'select'=>'title',
'condition'=>'postID=:postID',
'params'=>array(':postID'=>10),
));
findByAttributes 里的 $attributes就是字段的名字.
查询title为abc怎么查询呢?见下面
1 $criteria=new CDbCriteria; 2 $criteria->select='username'; // only select the 'title' column 3 $criteria->condition='username=:username'; 4 $criteria->params=array(':username=>'admin'); 5 $post=Post::model()->find($criteria); // $params is not needed
1 $admin=new Admin; 2 $admin->username=$username; 3 $admin->password=$password; 4 if($admin->save()>0){ 5 echo "添加成功"; 6 }else{ 7 echo "添加失败"; 8 }
1 Post::model()->updateAll($attributes,$condition,$params); 2 3 $count = Admin::model()->updateAll(array('username'=>'11111','password'=>'11111'),'password=:pass',array(':pass'=>'1111a1')); 4 if($count>0){ 5 echo "修改成功"; 6 }else{ 7 echo "修改失败"; 8 }
1 Post::model()->updateByPk($pk,$attributes,$condition,$params); 2 3 $count = Admin::model()->updateByPk(1,array('username'=>'admin','password'=>'admin')); 4 $count = Admin::model()->updateByPk(array(1,2),array('username'=>'admin','password'=>'admin'),'username=:name',array(':name'=>'admin')); 5 if($count>0){ 6 echo "修改成功"; 7 }else{ 8 echo "修改失败"; 9 }
1 Post::model()->updateCounters($counters,$condition,$params); 2 3 $count =Admin::model()->updateCounters(array('status'=>1),'username=:name',array(':name'=>'admin')); 4 if($count>0){ 5 echo "修改成功"; 6 }else{ 7 echo "修改失败"; 8 }
1 Post::model()->deleteAll($condition,$params); 2 3 $count = Admin::model()->deleteAll('username=:name and password=:pass',array(':name'=>'admin',':pass'=>'admin')); 4 $id=1,2,3 5 deleteAll('id in(".$id.")');删除id为这些的数据 6 if($count>0){ 7 echo "删除成功"; 8 }else{ 9 echo "删除失败"; 10 }
1 Post::model()->deleteByPk($pk,$condition,$params); 2 $count = Admin::model()->deleteByPk(1); 3 $count = Admin::model()->deleteByPk(array(1,2),'username=:name',array(':name'=>'admin')); 4 if($count>0){ 5 echo "删除成功"; 6 }else{ 7 echo "删除失败"; 8 }