您的位置:首页 > 编程语言 > PHP开发

Yii Framework 开发教程(25) 数据库-Query Builder示例

2014-01-19 10:01 507 查看


上一篇介绍PHP使用DAO(数据库访问对象接口)访问数据库的方法,使用DAO需要程序员编写SQL语句,对于一些复杂的SQL语句,Yii提供了Query Builder来帮助程序员生成SQL语句,Query Builder提供了一中面向对象的方法动态创建SQL语句,打个不十分恰当的比较,PHP 的DAO和.Net 的DAO接口非常类型,Query builder 就有点像LINQ了,尽管和LINQ比起来功能小很多。对于一些简单的SQL查询,通常不需要借助于Query Builder,比如上篇中的查询Employee表格。

和直接使用SQL语句相比,使用Query Builder具有下面好处:

支持通过程序动态创建比较复杂的SQL查询.

自动为创建的SQL语句中的表名,列表添加引号以避免和SQL保留的标志符产生冲突.

指定为参数添加引号并尽可能的使用参数绑定以减小SQL Injection的风险。.

使用Query Builder不直接编写SQL语句,而提供了一定程度上的数据库抽象,从而为切换数据库类型提供了便利。

本例查询Chinook的两个表Customer和Employee, 查询EmployeeId=4管理的所有客户的联系信息。

如果使用SQL查询,可以写作:

[sql]
view plaincopyprint?

SELECT c.FirstName, c.LastName , c.Address,c.Email
FROM customer c
INNER JOIN
employee e
ON c.SupportRepId=e.EmployeeId
WHERE e.EmployeeId=4

SELECT c.FirstName, c.LastName , c.Address,c.Email
FROM customer c
INNER JOIN
employee e
ON c.SupportRepId=e.EmployeeId
WHERE e.EmployeeId=4


本例使用Query Builder创建SQL查询,修改SiteController的indexAction方法:

[php]
view plaincopyprint?

public function actionIndex()
{

$model = array();
$connection=Yii::app()->db;
$command=$connection->createCommand()
->select('c.FirstName, c.LastName, c.Address,c.Email')
->from('customer c')
->join('employee e','c.SupportRepId=e.EmployeeId')
->where('e.EmployeeId=4');

$dataReader=$command->query();

// each $row is an array representing a row of data
foreach($dataReader as $row)
{
$customer= new DataModel();

$customer->firstName=$row['FirstName'];
$customer->lastName=$row['LastName'];

$customer->address=$row['Address'];
$customer->email=$row['Email'];

$model[]=$customer;
}

$this->render('index', array(
'model' => $model,

));
}

public function actionIndex()
{

	$model = array();
	$connection=Yii::app()->db;
	$command=$connection->createCommand()
		->select('c.FirstName, c.LastName, c.Address,c.Email')
		->from('customer c')
		->join('employee e','c.SupportRepId=e.EmployeeId')
		->where('e.EmployeeId=4');

	$dataReader=$command->query();

	// each $row is an array representing a row of data
	foreach($dataReader as $row)
	{
		$customer= new DataModel();

		$customer->firstName=$row['FirstName'];
		$customer->lastName=$row['LastName'];

		$customer->address=$row['Address'];
		$customer->email=$row['Email'];

		$model[]=$customer;
	}

	$this->render('index', array(
		'model' => $model,

		));
}


可以看到Query Builder也是使用 CDbCommandCDbCommand提供了如下查询数据的方法:

select()

selectDistinct()

from()

where()

join()

leftJoin()

rightJoin()

crossJoin()

naturalJoin()

group()

having()

order()

limit()

offset()

union()

此外数据定义方法:

createTable()

renameTable()

dropTable()

truncateTable()

addColumn()

renameColumn()

alterColumn()

dropColumn()

createIndex()

dropIndex()

可以看到CDbCommand支持的方法基本上和SQL语句的关键字一一对应,使不使用Query Builder全凭个人爱好,对应简单的SQL语句可以直接使用SQL语句,对于较复杂的查询可以借助于Query Builder。

本例显示结果:





本例下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: