1. PDO method of executing native SQL.
Copy code The code is as follows:
$sql = "";//Original sql statement
xx::model() ->dbConnection->createCommand($sql)->execute();
2. Active Record method
(1) New method
Copy the code The 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. 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.
Copy code The code is as follows:
$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 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:
Copy the code The 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 specified values, 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
Copy code 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();
http://www.bkjia.com/PHPjc/740218.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/740218.htmlTechArticle1. PDO method of executing native SQL. Copy the code as follows: $sql = "";//Original sql statement xx::model()-dbConnection-createCommand($sql)-execute(); 2. Active Record method (...