`
zhengdl126
  • 浏览: 2503953 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类

【Yii】数据库读写方法:AR模型和DAO方法

 
阅读更多

一、AR模型方法

AR模型是ORM方式的一种,其将SQL查询进行封装,使得数据库读写更加方便便捷。其中一个AR类代表数据库中的一张表。

1.类的定义(Model模型)

定义方式如下:

 
class Post extends CActiveRecord{
publicstaticfunction model($className=__CLASS__)
    {
return parent::model($className);
    }

publicfunction tableName()
    {
return 'tbl_post';}}
 

这是一个Model类的最小代码。

2.新增记录

 

$post=new Post;
$post->title='sample post';
$post->content='content for the sample post';
$post->create_time=time();
$post->save();

 

3.查询

查询语句比较复杂,主要有四种。

 

 
// find the first row satisfying the specified condition
$post=Post::model()->find($condition,$params);
// find the row with the specified primary key
$post=Post::model()->findByPk($postID,$condition,$params);
// find the row with the specified attribute values
$post=Post::model()->findByAttributes($attributes,$condition,$params);
// find the first row using the specified SQL statement
$post=Post::model()->findBySql($sql,$params);
 

 

其中$condition部分就是SQL语句的WHERE部分,$params就是$condition里面需要的参数。示例:

 

// find the row with postID=10
$post=Post::model()->find('postID=:postID', array(':postID'=>10));

 

同时也可以使用CDbCriteria类来配置查询条件。示例如下:

 

$criteria=new CDbCriteria;
$criteria->select='title';  // only select the 'title' column
$criteria->condition='postID=:postID';
$criteria->params=array(':postID'=>10);
$post=Post::model()->find($criteria); // $params is not needed

 

此时就无需$params参数了。

上述是查询单条记录,如果要查询多条记录则使用:

 

 
// find all rows satisfying the specified condition
$posts=Post::model()->findAll($condition,$params);
// find all rows with the specified primary keys
$posts=Post::model()->findAllByPk($postIDs,$condition,$params);
// find all rows with the specified attribute values
$posts=Post::model()->findAllByAttributes($attributes,$condition,$params);
// find all rows using the specified SQL statement
$posts=Post::model()->findAllBySql($sql,$params);
 

 

4.更新记录

更新记录也可以用save()函数。AR模型会智能判定,若对象由new创建则新建记录,若对象是从数据库中的查询结果,则save函数就变成了更新。

然而更新也有特定的函数:

 
// update the rows matching the specified condition
Post::model()->updateAll($attributes,$condition,$params);
// update the rows matching the specified condition and primary key(s)
Post::model()->updateByPk($pk,$attributes,$condition,$params);
// update counter columns in the rows satisfying the specified conditions
Post::model()->updateCounters($counters,$condition,$params);
 

 

5.删除记录

先查询后删除:

 

$post=Post::model()->findByPk(10); // assuming there is a post whose ID is 10
$post->delete(); // delete the row from the database table

 

直接删除:

// delete the rows matching the specified condition
Post::model()->deleteAll($condition,$params);
// delete the rows matching the specified condition and primary key(s)
Post::model()->deleteByPk($pk,$condition,$params);

 

6.从表单直接提交到数据库

如果数据表的项太多,插入新记录的时候参数列表可能会很长,这时候可以使用attributes属性来承接由表单POST过来的参数。(未测试)

 

// assume $_POST['Post'] is an array of column values indexed by column names
$post->attributes=$_POST['Post'];
$post->save();

 

7.函数重载

在 执行记录的时候可以伴随着函数调用,这些函数主要 有:beforeValidate, afterValidate, beforeSave, afterSave, beforeDelete, afterDelete, afterConstruct, beforeFind, afterFind, 函 数名可以看出是什么意思了。

8. 使用事务

事务可以将读写操作作为一个整体进行,有效防止数据库读写出错。

 

 
$model=Post::model();
$transaction=$model->dbConnection->beginTransaction();
try
{
// find and save are two steps which may be intervened by another request
    // we therefore use a transaction to ensure consistency and integrity
$post=$model->findByPk(10);
$post->title='new post title';
$post->save();
$transaction->commit();
}
catch(Exception$e)
{
$transaction->rollback();
}
 

 

二、DAO使用

DAO(数据访问对象)对访问存储在不同数据库管理系统(DBMS)中的数据提供了一个通用的API。因此,在将底层 DBMS 更换为另一个时,无需修改使用了 DAO 访问数据的代码。

上面看到AR的方式很方便和便捷,然而其只能处理简单数据模型,如果需要读写多个数据表或者设计联合查询,AR方式往往很有限,这时候就需要使用DAO方式。

1. 建立连接

 

$connection=new CDbConnection($dsn,$username,$password);
// 建立连接。你可以使用  try...catch 捕获可能抛出的异常
$connection->active=true;
......
$connection->active=false;  // 关闭连接

 

2.执行SQL语句

 

 
$connection=Yii::app()->db;   // 假设你已经建立了一个 "db" 连接
// 如果没有,你可能需要显式建立一个连接:
// $connection=new CDbConnection($dsn,$username,$password);
$command=$connection->createCommand($sql);
// 如果需要,此 SQL 语句可通过如下方式修改:
// $command->text=$newSQL;
$rowCount=$command->execute();   // 执行无查询 SQL
$dataReader=$command->query();   // 执行一个 SQL 查询
$rows=$command->queryAll();      // 查询并返回结果中的所有行
$row=$command->queryRow();       // 查询并返回结果中的第一行
$column=$command->queryColumn(); // 查询并返回结果中的第一列
$value=$command->queryScalar();  // 查询并返回结果中第一行的第一个字段
 

 

3.获取查询结果

 

 
$dataReader=$command->query();
// 重复调用 read() 直到它返回 false
while(($row=$dataReader->read())!==false) { ... }
// 使用 foreach 遍历数据中的每一行
foreach($dataReaderas$row) { ... }
// 一次性提取所有行到一个数组
$rows=$dataReader->readAll();
 

 

4.使用事务

 

 
$transaction=$connection->beginTransaction();
try
{
$connection->createCommand($sql1)->execute();
$connection->createCommand($sql2)->execute();
//.... other SQL executions
$transaction->commit();
}
catch(Exception$e) // 如果有一条查询失败,则会抛出异常
{
$transaction->rollBack();
}
 

 

5.绑定列

绑定列可以让当前查询结果和一个变量绑定,方便操作。

 

 
$sql="SELECT username, email FROM tbl_user";
$dataReader=$connection->createCommand($sql)->query();
// 使用 $username 变量绑定第一列 (username)
$dataReader->bindColumn(1,$username);
// 使用 $email 变量绑定第二列 (email)
$dataReader->bindColumn(2,$email);
while($dataReader->read()!==false)
{
// $username 和 $email 含有当前行中的 username 和 email
}

 

分享到:
评论

相关推荐

    php 框架yii 数据库 DAO

    yii DAO编程yii DAO编程yii DAO编程yii DAO编程yii DAO编程yii DAO编程yii DAO编程yii DAO编程

    yii2-schemadump:从现有数据库生成模式

    yii2-schemadump 从现有数据库生成模式。演示版要求PHP 7.3或更高版本Yii 2.x安装composer require --dev jamband/yii2-schemadump用法在config / console.php中添加以下内容: return [ . . . 'components' => [ . ...

    YII数据库操作大全

    yii对象操作、直接数据库操作、事物等操作。几乎所有的操作都收录了

    Yii实现多数据库主从读写分离的方法

    本文实例讲述了Yii实现多数据库主从读写分离的方法。分享给大家供大家参考。具体分析如下: Yii框架数据库多数据库、主从、读写分离 实现,功能描述: 1.实现主从数据库读写分离 主库:写 从库(可多个):读 2.主数据库...

    YII2数据库MySQL复制和读写分离配置

    关于YII2代码配置那一部分,给出的是官方的链接,如果想要这部分,请不用下载,直接去官方阅读,以免浪费资源分哦

    yii2-swoole:完整的解决方案,使yii2-framework与协程在swoole上运行

    yii2-swoole 为赋予 Yii2 框架协程异步能力而生。 后期开发会依赖 去实现功能,相信 Swoft 会是下一代优秀的框架。 此插件基于 swoole (v2.0) 底层实现的协程,改造 Yii2 的核心代码,使开发者无感知,以及在不改动...

    Yii数据库缓存实例分析

    本文实例讲述了Yii数据库缓存...Yii::app()->cache->set($key,$value,$outtime); //$key 唯一主键,$value 对应主键的值(可以是数组), $outtime 过期时间。 3、获取缓存 Yii::app()->cache->get($key); //设置数据

    yii2 数据库读写分离配置示例

    本篇文章主要介绍了yii2 数据库读写分离配置示例,数据库读写分离是在网站遇到性能瓶颈的时候最先考虑优化的步骤,有兴趣的可以了解一下。

    yii2-tree:Yii2 模型的树小部件

    yii2-树Yii2 模型的树小部件安装安装此扩展的首选方法是通过 。 要么跑 php composer.phar require --prefer-dist pendalf89/yii2-tree "*"或添加 "pendalf89/yii2-tree": "*"到composer.json文件的 require 部分。...

    yii2-curl:yii2框架的cURL包装器

    yii2-curl yii2框架的cURL包装器

    yii2-backup:Yii2的数据库备份和还原功能模块扩展

    Yii2备份和还原数据库 数据库备份和还原功能 安装 安装此扩展的首选方法是通过 。 无论运行 php composer.phar require --prefer-dist spanjeta/yii2-backup "*" 或添加 "spanjeta/yii2-backup": "*" 到composer....

    yii2-dialog:一种扩展,用于包装Yii 2.0框架的bootstrap3-dialog

    yii2-对话框 Yii Framework 2.0的小部件组件,可轻松配置和初始化弹出通知对话框。 它为本机javascript... 通过覆盖和增强使用yii的data-confirm方法的链接的确认对话框,可以呈现漂亮的对话框。 通过kartik\dialog

    yii2-comments:Yii2的评论模块

    yii2评论 Yii2的注释模块。 安装 安装此扩展的首选方法是通过 。 尝试 composer require "ogheo/yii2-comments:*" 或添加 "ogheo/yii2-comments": "*" 到composer.json文件的require部分。 配置 数据库迁移 ...

    yii2-staticactiverecord:Yii2 的 ActiveRecord 的更快但灵活性稍差的版本

    由于 ActiveRecord 的灵活性,许多计算必须在运行时完成:查找相应的数据库模式,从中导出属性列表,根据模型的rules()确定每个场景的安全属性列表,等等。 在 Yii2 的架构中,大多数这些计算不仅对您的每个 ...

    yii2-openapi:用于Yii2的REST API应用程序生成器,openapi 3.0 YAML-> Yii2

    yii2-openapi 用于Yii2的REST API应用... API模式更改时更新数据库和模型 要求 PHP 7.1或更高版本(与PHP 8兼容) 安装 composer require cebe/yii2-openapi:@beta cebe/php-openapi:@beta 用法 您可以在现有应用程

    yii数据库的查询方法

    主要介绍了yii数据库的查询方法,结合实例简单分析了直接查询和使用criteria进行查询的技巧,需要的朋友可以参考下

    yii2-layer:yii2的图层资产

    yii2层yii2层安装安装此扩展的首选方法是通过 。 无论运行 php composer.phar require --prefer-dist xinyeweb/yii2-layer:dev-master或添加 "xinyeweb/yii2-layer": "dev-master"到composer.json文件的require部分...

    yii2-knockoutjs:Yii2 的淘汰赛资产

    Yii2 的淘汰赛资产提供易于集成的资产包到您的Yii2应用。安装安装此扩展的首选方法是通过 。 无论运行composer require --prefer-dist " madand/yii2-knockoutjs:* " 或添加 "madand/yii2-knockoutjs": "*"到...

Global site tag (gtag.js) - Google Analytics