YII 采用 ORM(object-Relation Mapping)的设计模式进行数据库编程。
配置数据库连接 在 protected/config/main.php 文件中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| 'db'=>array( 'connectionString'=>'mysql:host=localhost;dbname=testdrive', 'emulatePreare'=>true, 'username'=>'root', 'password'=>'', 'charset'=>'utf8', ),```
定义数据库操作类:models
```php <?php
class User extends CActiveRecord{ public static function model(__CLASS__){ return parent::model($className); }
public function tableName(){ return '{{User}}'; } } ?>
|
实例化数据库操作类:controllers
1 2 3 4 5 6 7 8 9 10 11 12 13
| <?php class UserController extends Controller{ public function actionIndex(){ $model = new User; $model->username = 'admin'; $model->password = '123456'; $model->email = '[email protected]'; var_dump($model->save()); exit; $this->render('index'); } } ?>
|
读取记录:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
$user = User::model->find($condition,$params);
$user = User::model->findByPk($postId,$condition,$params);
$user = User::model->findByAttributes($attributes,$condition,$params);
$user = User::model->findBySql($sql,$params);
$posts=Post::model()->findAll($condition,$params);
$posts=Post::model()->findAllByPk($postIDs,$condition,$params);
$posts=Post::model()->findAllByAttributes($attributes,$condition,$params);
$posts=Post::model()->findAllBySql($sql,$params);
|
我们可以让$condition 成为一个 CDbCriteria 的实例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| $criteria = new CDbCriteria;
$criteria->select = 'title';
$criteria->condition = 'postID=:postID';
$criteria->params = array(':postID'=>10);
$post = Post::model->find($criteria);
$n=Post::model()->count($condition,$params);
$n=Post::model()->countBySql($sql,$params);
$exists=Post::model()->exists($condition,$params);
|
更新记录:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| $post = Post::model->findByPk(10);
$post->title = 'new post title';
$post->save();
Post::model->updateAll($attributes,$condition,$params);
Post::model->updateByPk($pk,$attributes,$condition,$params);
Post::model->updateCounters($counters,$condition,$params);
|
删除数据:
1 2 3 4 5 6 7 8 9 10 11
| $post=Post::model()->findByPk(10);
$post->delete();
Post::model()->deleteAll($condition,$params);
Post::model()->deleteByPk($pk,$condition,$params);
|