总所周知
modelName::model() -> find() <span>//</span><span>找出的是一个对象</span> modelName::model() -> findALL() <span>//</span><span>找出的是一个对象集合的数组</span>
如何找出我所需要的字段的数据,而不是全部字段的数据
之前我是这么做的
<span>$criteria</span> = <span>new</span><span> CDbCriteria; </span><span>$criteria</span>->select = 'username,id,email'<span>; </span><span>$criteria</span>->order = 'id DESC'<span>; </span><span>$users</span> = modelName::model()->findAll( <span>$criteria</span> );
后台无意中看到别人有这么写的,发现自己是多么的无知
<span>$users</span> = modelName::model()->findAll(<span>array</span><span>( </span>'select' =><span>array</span>('username','id','email'), 'order' => 'id DESC',<span> ));</span>
测试后发现果然可以用,那么find也可以这么操作
<span>$user</span> = modelName::model()->find(<span>array</span><span>( </span>'select' =><span>array</span>('username','id','email'), 'order' => 'id DESC', 'condition' => 'id='.$id,<span> ));</span>
当然了,这么做肯定不安全了,换成下面的方法同样可以
<span>$users</span> = <span>$this</span>->user->find(<span>array</span><span>( </span>'select'=><span>array</span>('id','username','email'), 'order' => 'id DESC', 'condition' => 'state=:state AND id=:id', 'params' => <span>array</span>(':state'=>'1',':id' => '2'),<span> ));</span>
同理用findAll测试了也可以,结论
通过这种方法能够很方便的获取所需要的数据,当然需要分页的时候还是 需要 new 以下 CDbCriteria 的
$retrievedProject=Project::model()->findall();
foreach($retrievedProject as $v){
echo $v->attributes['title'];
}
这样写:
$db = new CDbCriteria();
$db->addInCondition('id', array(1,2,3));
$newstypelist=NewsType::model()->findAll($db);