Yii operates a database in three ways

  • 2021-01-22 04:54:52
  • OfStack

1. Implement the PDO mode of native SQL.
$sql = "";// The original ecological sql statements  
xx::model()->dbConnection->createCommand($sql)->execute(); 

2. Active Record mode
(1) New way
$post=new Post; 
$post->title='sample post'; 
$post->content='post body content'; 
$post->save(); 

(2) Criteria way
You can also specify more complex query conditions using $condition. Instead of using strings, we can make $condition an instance of CDbCriteria, which allows us to specify conditions that are not limited to WHERE.
$criteria=new CDbCriteria; 
$criteria->select='title';  //  Select only  'title'  column  
$criteria->condition='postID=:postID'; 
$criteria->params=array(':postID'=>10); 
$post=Post::model()->find($criteria);

An alternative to CDbCriteria is to pass an array to the find method. The array's keys and values correspond to the standard (criterion) attribute names and values. The above example could be rewritten as follows:
$post=Post::model()->find(array( 
    'select'=>'title', 
    'condition'=>'postID=:postID', 
    'params'=>array(':postID'=>10), 
)); 

We can use findByAttributes() when one query condition is about matching several columns with a specified value. We make the $attributes argument an array of values indexed by column name. In some frameworks, this task can be accomplished by calling methods like findByNameAndTitle. While this approach may seem tempting, it often causes confusion, conflicts, and case-sensitive issues such as column names.
3. Query Builder mode
$user = Yii::app()->db->createCommand() 
    ->select('id, username, profile') 
    ->from('tbl_user u') 
    ->join('tbl_profile p', 'u.id=p.user_id') 
    ->where('id=:id', array(':id'=>$id)) 
    ->queryRow();

Related articles: