Home > Backend Development > PHP Tutorial > Yii框架中 find findAll 查找出制定的字段的方法对比_PHP

Yii框架中 find findAll 查找出制定的字段的方法对比_PHP

WBOY
Release: 2016-05-31 19:30:02
Original
1053 people have browsed it

众所周知

modelName::model() -> find()    //找出的是一个对象
modelName::model() -> findALL()  //找出的是一个对象集合的数组
如何找出我所需要的字段的数据,而不是全部字段的数据

之前我是这么做的

$criteria = new CDbCriteria;
$criteria->select = 'username,id,email';
$criteria->order = 'id DESC';
$users = modelName::model()->findAll( $criteria );
Copy after login

后台无意中看到别人有这么写的,发现自己是多么的无知

$users = modelName::model()->findAll(array(
  'select' =>array('username','id','email'),
  'order' => 'id DESC', 
));
Copy after login

测试后发现果然可以用,那么find也可以这么操作

$user = modelName::model()->find(array(
  'select' =>array('username','id','email'),
  'order' => 'id DESC',
  'condition' => 'id='.$id,
));
Copy after login

当然了,这么做肯定不安全了,换成下面的方法同样可以

$users = $this->user->find(array(
  'select'=>array('id','username','email'),
  'order' => 'id DESC',
  'condition' => 'state=:state AND id=:id',
  'params' => array(':state'=>'1',':id' => '2'),
));
Copy after login

同理用findAll测试了也可以,结论

通过这种方法能够很方便的获取所需要的数据,当然需要分页的时候还是 需要 new 以下 CDbCriteria 的

比如我要取出videoinfo表中的'v_id','title','big_class','sub_class','upload_time','comment_num' 等字段,且条件是status=1的,按照lastmodifytime倒序,且只取出3条即可,这样操作:

$criteria = new CDbCriteria() ; 
$criteria -> select = array('v_id','title','big_class','sub_class','upload_time','comment_num');     
$criteria -> condition = 'status = 1'; 
$criteria -> order = 'lastmodifytime desc'; 
$criteria -> limit = 3; 
 $criteria ->params = array (':status' => $你的变量) ; 
$result = VideoInfo::model()->findAll($criteria); 
Copy after login

其中我注释掉的那一行是可以传变量的,用占位符表示,比如你的status需要按照变量来条件赋值的话,可以在注释的那行赋值,然后在condition条件写成

$criteria -> condition = 'status = :status'; 
Copy after login

即可,
这样,$result变量时你取得的结果,它是个对象列表,需要遍历一下:

foreach ($result as $ob){ 
      print_r($ob->attributes); 
 } 
Copy after login

比如你想展示每个字段只需打出

$ob->attributes['title']; 
Copy after login

等等即可

领完,CPagination类可以和CDbCriteria类以及前台的分页插件一起用来支持分页:

      $count =VideoInfo::model()->count($criteria)

      $pages=new CPagination($count);    
      $pages->pageSize=30; //每页分多少条
      $pages->applyLimit($criteria); 

Copy after login

$result = VideoInfo::model()->findAll($criteria); 
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template