Home> PHP Framework> YII> body text

Three ways to operate the database in yii

王林
Release: 2020-02-17 16:36:15
Original
2299 people have browsed it

Three ways to operate the database in yii

1. PDO method of executing native SQL

The code is as follows:

$sql = "";//原生态sql语句 xx::model()->dbConnection->createCommand($sql)->execute();
Copy after login

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();
Copy after login

(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);
Copy after login

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), ));
Copy after login

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();
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!