1. PDO method of executing native SQL
The code is as follows:
$sql = "";//原生态sql语句 xx::model()->dbConnection->createCommand($sql)->execute();
2. Active Record Method
(1) New method
The code is as follows:
$post=new Post; $post->title='sample post'; $post->content='post body content'; $post->save();
(Related tutorials recommended:yii framework)
(2) Criteria method
You can also use $condition to specify more complex query conditions. Instead of using a string, we can make $condition an instance of CDbCriteria, which allows us to specify conditions that are not limited to WHERE.
The code is as follows:
$criteria=new CDbCriteria; $criteria->select='title'; // 只选择 'title' 列 $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 respectively correspond to the attribute names and values of the criterion. The above example can be rewritten 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 a 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. Although this approach seems tempting, it often causes confusion, conflicts, and issues such as case-sensitivity of column names.
3. Query Builder method
The code is as follows:
$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();
If you want to learn more programming related content, please pay attention to php Chinese websiteProgramming Tutorialcolumn!
The above is the detailed content of Three ways to operate the database in yii. For more information, please follow other related articles on the PHP Chinese website!