SoFunction
Updated on 2025-03-09

3 ways to operate a database

1. Execute native SQL PDO method.

Copy the codeThe code is as follows:
$sql = "";//Original SQL statement
xx::model()->dbConnection->createCommand($sql)->execute();

2. Active Record method
(1)New method
Copy the codeThe code is as follows:
$post=new Post;
$post->title='sample post';
$post->content='post body content';
$post->save();

(2) Criteria method
You can also use $condition to specify more complex query conditions. Without using strings, we can make $condition an instance of CDbCriteria, which allows us to specify conditions that are not limited to WHERE.
Copy the codeThe code is as follows:
$criteria=new CDbCriteria;
$criteria->select='title';  // Select only the '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 keys and values ​​of the array correspond to the attribute names and values ​​of the criteria. The above example can be rewritten as follows:
Copy the codeThe code is as follows:
$post=Post::model()->find(array(
    'select'=>'title',
    'condition'=>'postID=:postID',
    'params'=>array(':postID'=>10),
));

When a query condition is about matching several columns by the specified value, we can use findByAttributes(). We make the $attributes parameter an array of values ​​indexed by column names. In some frameworks, this task can be achieved by calling a method like findByNameAndTitle. But it often causes confusion, conflicts and, for example, case-sensitive column names.
3. Query Builder method
Copy the codeThe code is as follows:
$user = Yii::app()->db->createCommand()
    ->select('id, username, profile')
    ->from('tbl_user u')
    ->join('tbl_profile p', '=p.user_id')
    ->where('id=:id', array(':id'=>$id))
    ->queryRow();