Yii uses find findAll to find out the implementation of the specified field

  • 2021-07-18 07:24:27
  • OfStack

This article shows the implementation method of Yii using find findAll to find out the specified field in the form of an example, and shares it with everyone for reference. The specific methods are as follows:

As we all know, the following methods are adopted:


modelName::model() -> find()        // What I found out is that 1 Objects 
modelName::model() -> findALL()    // What I found out is that 1 An array of collections of objects 

You can find arrays of objects and collections of objects, so how do you find the data for the fields I need, not the data for all the fields? This is what I did before:


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

The background accidentally saw someone else write this, and the method is very good:


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

After testing, it is found that it can be used, so find can also operate like this:


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

Of course, it is definitely not safe to do so. It is also possible to change to the following methods:


$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'),
));

Similarly, it can be tested with findAll.

Conclusions:

Through this method, we can easily obtain the required data. Of course, when we need paging, we still need CDbCriteria under new 1.

I hope this article to use Yii database programming can be helpful.


Related articles: