yii framework:Query Builder 中文教程
2015-10-22 18:04
525 查看
声明:本文翻译自yiiframework官网的Query Builder文档,yii框架版本v1.1,网址:“http://www.yiiframework.com/doc/guide/1.1/zh_cn/database.query-builder”。
Query Builder,我们可以翻译成(数据库)查询助手,不知道有没有官方的翻译方法,暂且先这么翻译吧。
以下开始翻译文档正文。
----------------------------------------------------------------------------------------------------------------------------------------------------
查询助手初体验
创建数据检索查询
创建数据处理查询
创建表操作查询
Yii查询助手提供了一种完全面向对象的方式来编写SQL语句。它使得开发者可以使用类的方法和属性来操作SQL语句的各个组成部分。查询助手会将这些不同的SQL语句组成部分组合在一起,形成一个完整、有效的SQL语句,并调用DAO的相关方法来执行。下面展示了一个典型的使用查询助手来创建一个SELECT语句的用法:
查询助手的最佳使用场景是,程序上地组装一条SQL语句,或者基于你的应用上的一些条件逻辑。(译者注:原文这话有点别扭,我个人的理解是,在我们的程序中,我们需要根据一些变量带入SQL语句执行相关数据库操作,通过查询助手,我们可以轻松做到这一点,并且不用编写完整的SQL语句,以免造成语法错误导致程序无法执行。)使用查询助手的好处主要包括:
它可以帮助我们在程序上创建复杂的SQL语句。
它自动引入数据表名和字段名,以免出现SQL预留字和特殊字符的冲突问题。
在必要的时候,它会引入参数值并绑定参数,以降低SQL注入攻击的风险。
它提供了一定程度上的数据库抽象,来简化在不同的数据库平台之间的迁移工作。
使用查询助手并不是强制和必须的,实际上,如果你的查询非常简单,直接编写SQL语句反而更简单快速。
#########################################################################################
注意:查询助手不能用来变更一个已存在的通过SQL语句来执行的查询。举个例子,下面的代码将不会起作用:
再强调一点,不要把查询助手和普通的SQL语句进行混用。
#########################################################################################
开始使用查询助手,我们首先创建一下CDbCommand的实例,如下:
我们使用Yii::app()->db来获取数据库连接,并且调用CDbConnection::createCommand()方法来创建所需的指令实例。
在DAO操作中,我们会给createCommand()方法传入一个完整的SQL语句,但是在查询助手的使用过程中,我们传空值即可。因为,我们要使用查询助手的方法来创建SQL语句的每一个组成部分。下面的部分会进行详细讲解。
select():
指定查询的SELECT部分
selectDistinct():
指定查询的SELECT部分,并开启DISTINCT标识
from():指定查询的FROM部分
where():指定查询的WHERE部分
andWhere():
在WHERE部分使用AND操作符添加一个条件
orWhere():在WHERE部分使用OR操作符添加一个条件
join():
添加内联查询部分
leftJoin():
添加左联查询部分
rightJoin():添加右联查询部分
crossJoin():添加CROSS JOIN查询部分
naturalJoin():添加NATURAL
JOIN查询部分
group():添加GROUP
BY查询部分
having():添加HAVING查询部分
order():添加ORDER查询部分
limit():添加LIMIT查询部分
offset():添加OFFSET查询部分
union():
添加联合查询部分
(译者注:由于本人对数据库操作懂的不算多,所以,以上部分的SELECT操作,有部分未翻译,一是不知道如何翻译才准确,二是怕翻译错了反而误导了大家,大家就当没看到啊哈哈。)
接下来,我们会讲解如何使用查询助手的方法。简单起见,我们假设下面的DB操作都是基于MySQL的。
注意,如果你使用的是其他DBMS,在下面的例子中展示的表、字段和值的引用方法可能会不同。
select()方法指定了查询的SELECT部分。参数$columns指定了查询选择的字段,该参数可以使用一个包含多个字段并且使用逗号分隔的字符串,也可以使用包含多个字段名的数组。字段名可以包含表前缀和/或字段别名。该方法会自动引入字段名,除非一个字段包含了一些插入符(说明该字段是一个DB表达式)。
下面是一些例子:
selectDistinct()方法和select()方法类似,除了它会打开DISTINCT标识。举个例子,selectDistinct('id, username')将会生成如下SQL:
from()方法指定了查询的FROM部分。$tables参数指定了要在哪些表中进行查询,它可以是使用逗号分隔的、多个表名组成的字符串,也可以是包含多个表名的数组。表名可以包含前缀(如 public.tbl_user),和/或表的别名(如 tbl_user u)。该方法会自动引入表名,除非一个字段包含了一些插入符(说明该表是一个DB表达式或子查询)。
下面是一些例子:
where()方法指定了查询的WHERE部分。$conditions指定了查询条件,$params指定了整个查询中的参数值。$conditions参数可以是一个字符串,或者类似如下格式的数组:
其中,operator项可以是以下任意一种:
and:
operand会被AND操作符连接在一起。举个例子,
or: 用法和and类似,只不过连接符变成了OR。
in: operand 1应该是一个字段或DB表达式,operand 2是一个表示 operand1的值所在范围的一个数组。举个例子,
not in: 类似in,in表示包含在某个范围内的值,not in指不包含在某个范围内的值。
like: operand 1应该是一个字段或DB表达式,operand 2是一个表示 operand1的值所在范围的一个数组或字符串。举个例子,
not like: 类似like。只不过对like的判断范围取反。
or like: 类似like,只不过当like的operand 2为一个数组时,连接该数组中的多个判断值的不是AND,而是OR。
or not like: 类似not like,只不过当like的operand 2为一个数组时,连接该数组中的多个判断值的不是AND,而是OR。
一下是使用where()的一些例子:
注意,当操作符operand包含like的时候,我们必须明确的在operand 2中指定通配符(比如%和_)。如果operand 2的值来自如用户的输入,我们应该使用下面的代码对特殊字符进行编码,以免把用户输入的特殊字符,如%和_误认为是通配符:
andWhere()方法会将参数中的判断条件添加到WHERE部分,并与已有的WHERE判断条件使用AND操作符连接起来。该函数的用法基本上和where()一致,只不过该函数是向WHERE部分添加判断条件,而不是替换之前的判断条件。
orWhere()方法会将参数中的判断条件添加到WHERE部分,并与已有的WHERE判断条件使用OR操作符连接起来。该函数的用法基本上和where()一致,只不过该函数是向WHERE部分添加判断条件,而不是替换之前的判断条件。
order()函数指定了SELECT的ORDER BY部分。参数$columns可以是由逗号分隔开的多个字段以及排序方向(ASC或DESC)组成的字符串,也可以是包含多个字段和排序方向的数组。字段名可以包含表前缀。该方法会自动引入字段名,除非一个字段包含了一些插入符(说明该表是一个DB表达式或子查询)。
下面是一些例子:
limit()和offset()函数指定了SELECT的LIMIT和OFFSET部分。
注意,一些DBMS可能不支持LIMIT和OFFSET语法,在这种情况下,查询助手会重写整个SQL语句来模拟limit和offset功能。
下面是一些例子:
join()方法和它的相关变体,指定了如何使用
$table参数指定了关联哪张表。表名可以包含表前缀和/或别名。该方法会引入表名,除非它包含了插入符,这意味着它可能是一个DB表达式或子查询。
$conditions参数指定了关联条件,它的语法类似where()。
$params参数指定了绑定到整个查询中的参数值。
和其他查询助手方法不同,每个join方法调用都会被追加到之前的join中。
以下是一些例子:
group()函数指定了查询的GROUP BY部分。
$columns参数指定了进行分组的列。它既可以是使用逗号分开的多个字段组成的字符串,或者是一个包含多个字段的数组。字段名可以包含表前缀。
该方法会自动引入字段名,除非它包含了圆括弧,这意味着它可能是一个DB表达式。
下面是一些例子:
having()函数指定了查询的HAVING部分。它的使用方法类似where().
下面是一些实例:
union()函数指定了查询的UNION部分。它使用UNION操作符添加$sql到已有的SQL中。
调用union()函数多次,将会添加多个$sql到已存在的SQL中。
以下是一些例子:
相应这些查询操作,查询助手分别提供了insert, update和delete方法。
不同于上面描述的SELECT查询方法,每个数据处理查询方法,都为创建一个完整的SQL语句并且立即执行。
[insert()|CDbCommand::insert]: 在表中插入一行
[update()|CDbCommand::update]: 更新表中数据
[delete()|CDbCommand::delete]: 从表中删除数据
下面,我们一一介绍这些数据处理方法。
[insert()|CDbCommand::insert]方法创建并执行一条INSERT SQL语句。
$table参数指定了将数据插入哪张表,
$column参数,指定了要往表中插入的数据,以键值对数组的方式呈现。
下面是一个例子:
update()方法创建并执行了一个UPDATE操作的SQL语句。
$table参数指定了要更新的表。
$column参数指定了用来更新字段值的键值对数组。
$condition和$param字段类似where()操作,指定UPDATE SQL语句的where部分。
该方法会引入表名,并且使用参数绑定要更新的数据。
下面是一个例子:
delete()方法创建并执行了一个DELETE操作的SQL语句。
$table参数指定了要从哪张表里删除数据。
$condition和$param字段类似where()操作,指定DELETE SQL语句的where部分。
该方法会引入表名。
下面是一个例子:
Besides normal data retrieval and manipulation queries, the query builder also offers a set of methods for building and executing SQL queries that can manipulate the schema of a database. In particular, it supports the following queries:
createTable():
creates a table
renameTable():
renames a table
dropTable(): drops
a table
truncateTable():
truncates a table
addColumn(): adds
a table column
renameColumn():
renames a table column
alterColumn():
alters a table column
addForeignKey():
adds a foreign key (available since 1.1.6)
dropForeignKey():
drops a foreign key (available since 1.1.6)
dropColumn(): drops
a table column
createIndex():
creates an index
dropIndex(): drops
an index
Info: Although the actual SQL statements for manipulating database schema vary widely across different DBMS, the query builder attempts to
provide a uniform interface for building these queries. This simplifies the task of migrating a database from one DBMS to another.
The query builder introduces a set of abstract data types that can be used in defining table columns. Unlike the physical data types that are specific to particular DBMS and are quite different in different DBMS, the abstract data types are independent of DBMS.
When abstract data types are used in defining table columns, the query builder will convert them into the corresponding physical data types.
The following abstract data types are supported by the query builder.
a generic primary key type, will be converted into
string type, will be converted into
MySQL;
text type (long string), will be converted into
MySQL;
integer type, will be converted into
MySQL;
floating number type, will be converted into
MySQL;
decimal number type, will be converted into
MySQL;
datetime type, will be converted into
MySQL;
timestamp type, will be converted into
MySQL;
time type, will be converted into
MySQL;
date type, will be converted into
MySQL;
binary data type, will be converted into
MySQL;
boolean type, will be converted into
MySQL;
money/currency type, will be converted into
MySQL. This type has been available since version 1.1.8.
The createTable() method
builds and executes a SQL statement for creating a table. The
specifies the name of the table to be created. The
specifies the columns in the new table. They must be given as name-definition pairs (e.g.
The
specifies any extra SQL fragment that should be appended to the generated SQL. The query builder will quote the table name as well as the column names properly.
When specifying a column definition, one can use an abstract data type as described above. The query builder will convert the abstract data type into the corresponding physical data type, according to the currently used DBMS. For example,
be converted into
MySQL.
A column definition can also contain non-abstract data type or specifications. They will be put in the generated SQL without any change. For example,
not an abstract data type, and if used in a column definition, it will appear as is in the resulting SQL; and
converted).
Below is an example showing how to create a table:
The renameTable() method
builds and executes a SQL statement for renaming a table. The
specifies the name of the table to be renamed. The
specifies the new name of the table. The query builder will quote the table names properly.
Below is an example showing how to rename a table:
The dropTable() method
builds and executes a SQL statement for dropping a table. The
specifies the name of the table to be dropped. The query builder will quote the table name properly.
Below is an example showing how to drop a table:
The truncateTable() method
builds and executes a SQL statement for truncating a table. The
specifies the name of the table to be truncated. The query builder will quote the table name properly.
Below is an example showing how to truncate a table:
The addColumn() method
builds and executes a SQL statement for adding a new table column. The
specifies the name of the table that the new column will be added to. The
specifies the name of the new column. And
the definition of the new column. Column definition can contain abstract data type, as described in the subsection of "createTable". The query builder will quote the table name as well as the column name properly.
Below is an example showing how to add a table column:
The dropColumn() method
builds and executes a SQL statement for dropping a table column. The
specifies the name of the table whose column is to be dropped. The
specifies the name of the column to be dropped. The query builder will quote the table name as well as the column name properly.
Below is an example showing how to drop a table column:
The renameColumn() method
builds and executes a SQL statement for renaming a table column. The
specifies the name of the table whose column is to be renamed. The
specifies the old column name. And
the new column name. The query builder will quote the table name as well as the column names properly.
Below is an example showing how to rename a table column:
The alterColumn() method
builds and executes a SQL statement for altering a table column. The
specifies the name of the table whose column is to be altered. The
specifies the name of the column to be altered. And
the new definition of the column. Column definition can contain abstract data type, as described in the subsection of "createTable". The query builder will quote the table name as well as the column name properly.
Below is an example showing how to alter a table column:
The addForeignKey() method
builds and executes a SQL statement for adding a foreign key constraint to a table. The
specifies the name of the foreign key. The
specify the table name and column name that the foreign key is about. If there are multiple columns, they should be separated by comma characters. The
specify the table name and column name that the foreign key references. The
specify the
Below is an example showing how to add a foreign key constraint,
The dropForeignKey() method
builds and executes a SQL statement for dropping a foreign key constraint. The
specifies the name of the foreign key constraint to be dropped. The
specifies the name of the table that the foreign key is on. The query builder will quote the table name as well as the constraint names properly.
Below is an example showing how to drop a foreign key constraint:
The createIndex() method
builds and executes a SQL statement for creating an index. The
specifies the name of the index to be created. The
specifies the name of the table that the index is on. The
specifies the name of the column to be indexed. And the
specifies whether a unique index should be created. If the index consists of multiple columns, they must be separated by commas. The query builder will properly quote the table name, index name and column name(s).
Below is an example showing how to create an index:
The dropIndex() method
builds and executes a SQL statement for dropping an index. The
specifies the name of the index to be dropped. The
specifies the name of the table that the index is on. The query builder will quote the table name as well as the index names properly.
Below is an example showing how to drop an index:
Query Builder,我们可以翻译成(数据库)查询助手,不知道有没有官方的翻译方法,暂且先这么翻译吧。
以下开始翻译文档正文。
----------------------------------------------------------------------------------------------------------------------------------------------------
查询助手初体验
创建数据检索查询
创建数据处理查询
创建表操作查询
Yii查询助手提供了一种完全面向对象的方式来编写SQL语句。它使得开发者可以使用类的方法和属性来操作SQL语句的各个组成部分。查询助手会将这些不同的SQL语句组成部分组合在一起,形成一个完整、有效的SQL语句,并调用DAO的相关方法来执行。下面展示了一个典型的使用查询助手来创建一个SELECT语句的用法:
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;"><span style="font-family:Tahoma;font-size:12px;">$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();</span></span></span>
查询助手的最佳使用场景是,程序上地组装一条SQL语句,或者基于你的应用上的一些条件逻辑。(译者注:原文这话有点别扭,我个人的理解是,在我们的程序中,我们需要根据一些变量带入SQL语句执行相关数据库操作,通过查询助手,我们可以轻松做到这一点,并且不用编写完整的SQL语句,以免造成语法错误导致程序无法执行。)使用查询助手的好处主要包括:
它可以帮助我们在程序上创建复杂的SQL语句。
它自动引入数据表名和字段名,以免出现SQL预留字和特殊字符的冲突问题。
在必要的时候,它会引入参数值并绑定参数,以降低SQL注入攻击的风险。
它提供了一定程度上的数据库抽象,来简化在不同的数据库平台之间的迁移工作。
使用查询助手并不是强制和必须的,实际上,如果你的查询非常简单,直接编写SQL语句反而更简单快速。
#########################################################################################
注意:查询助手不能用来变更一个已存在的通过SQL语句来执行的查询。举个例子,下面的代码将不会起作用:
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">$command = Yii::app()->db->createCommand('SELECT * FROM tbl_user'); // the following line will NOT append WHERE clause to the above SQL</span></span>
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">//译者注:下面一行的代码并不会起作用,因为上面一行的查询指令是通过SQL语句来创建的,不能和查询助手的方法进行混用。 $command->where('id=:id', array(':id'=>$id));</span></span>
再强调一点,不要把查询助手和普通的SQL语句进行混用。
#########################################################################################
1. 查询助手初体验
Yii查询助手以CDbCommand的方式提供,主要的查询类都在DAO。开始使用查询助手,我们首先创建一下CDbCommand的实例,如下:
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;"><span style="font-family:Tahoma;font-size:12px;">$command = Yii::app()->db->createCommand();</span></span></span>
我们使用Yii::app()->db来获取数据库连接,并且调用CDbConnection::createCommand()方法来创建所需的指令实例。
在DAO操作中,我们会给createCommand()方法传入一个完整的SQL语句,但是在查询助手的使用过程中,我们传空值即可。因为,我们要使用查询助手的方法来创建SQL语句的每一个组成部分。下面的部分会进行详细讲解。
2. 创建数据检索查询
数据检索查询值得是SQL的SELECT操作。查询助手提供了一系列的方法来创建一个SELECT语句的各个组成部分。因为所有的这些方法都返回的是CDbCommand实例,所以,我们可以使用方法链来调用他们。就像本文刚开始的时候展示的例子一样。select():
指定查询的SELECT部分
selectDistinct():
指定查询的SELECT部分,并开启DISTINCT标识
from():指定查询的FROM部分
where():指定查询的WHERE部分
andWhere():
在WHERE部分使用AND操作符添加一个条件
orWhere():在WHERE部分使用OR操作符添加一个条件
join():
添加内联查询部分
leftJoin():
添加左联查询部分
rightJoin():添加右联查询部分
crossJoin():添加CROSS JOIN查询部分
naturalJoin():添加NATURAL
JOIN查询部分
group():添加GROUP
BY查询部分
having():添加HAVING查询部分
order():添加ORDER查询部分
limit():添加LIMIT查询部分
offset():添加OFFSET查询部分
union():
添加联合查询部分
(译者注:由于本人对数据库操作懂的不算多,所以,以上部分的SELECT操作,有部分未翻译,一是不知道如何翻译才准确,二是怕翻译错了反而误导了大家,大家就当没看到啊哈哈。)
接下来,我们会讲解如何使用查询助手的方法。简单起见,我们假设下面的DB操作都是基于MySQL的。
注意,如果你使用的是其他DBMS,在下面的例子中展示的表、字段和值的引用方法可能会不同。
select()
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">function select($columns='*')</span></span>
select()方法指定了查询的SELECT部分。参数$columns指定了查询选择的字段,该参数可以使用一个包含多个字段并且使用逗号分隔的字符串,也可以使用包含多个字段名的数组。字段名可以包含表前缀和/或字段别名。该方法会自动引入字段名,除非一个字段包含了一些插入符(说明该字段是一个DB表达式)。
下面是一些例子:
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">// SELECT * select() // SELECT `id`, `username` select('id, username') // SELECT `tbl_user`.`id`, `username` AS `name` select('tbl_user.id, username as name') // SELECT `id`, `username` select(array('id', 'username')) // SELECT `id`, count(*) as num select(array('id', 'count(*) as num'))</span></span>
selectDistinct()
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">function selectDistinct($columns)</span></span>
selectDistinct()方法和select()方法类似,除了它会打开DISTINCT标识。举个例子,selectDistinct('id, username')将会生成如下SQL:
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">SELECT DISTINCT `id`, `username`</span></span>
from()
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">function from($tables)</span></span>
from()方法指定了查询的FROM部分。$tables参数指定了要在哪些表中进行查询,它可以是使用逗号分隔的、多个表名组成的字符串,也可以是包含多个表名的数组。表名可以包含前缀(如 public.tbl_user),和/或表的别名(如 tbl_user u)。该方法会自动引入表名,除非一个字段包含了一些插入符(说明该表是一个DB表达式或子查询)。
下面是一些例子:
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">// FROM `tbl_user` from('tbl_user') // FROM `tbl_user` `u`, `public`.`tbl_profile` `p` from('tbl_user u, public.tbl_profile p') // FROM `tbl_user`, `tbl_profile` from(array('tbl_user', 'tbl_profile')) // FROM `tbl_user`, (select * from tbl_profile) p from(array('tbl_user', '(select * from tbl_profile) p'))</span></span>
where()
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">function where($conditions, $params=array())</span></span>
where()方法指定了查询的WHERE部分。$conditions指定了查询条件,$params指定了整个查询中的参数值。$conditions参数可以是一个字符串,或者类似如下格式的数组:
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">array(operator, operand1, operand2, ...)</span></span>
其中,operator项可以是以下任意一种:
and:
operand会被AND操作符连接在一起。举个例子,
array('and', 'id=1', 'id=2')将会生成
id=1 AND id=2。如果operand是一个数组,它将会使用相同的规则转换成字符串。例如,array('and', 'type=1', array('or', 'id=1', 'id=2'))将会生成
type=1 AND (id=1 OR id=2)。该方法不会做任何的编码或引用。
or: 用法和and类似,只不过连接符变成了OR。
in: operand 1应该是一个字段或DB表达式,operand 2是一个表示 operand1的值所在范围的一个数组。举个例子,
array('in', 'id', array(1,2,3))将会生成
id IN (1,2,3)。该方法会正确的引用字段名并对IN范围值进行编码。
not in: 类似in,in表示包含在某个范围内的值,not in指不包含在某个范围内的值。
like: operand 1应该是一个字段或DB表达式,operand 2是一个表示 operand1的值所在范围的一个数组或字符串。举个例子,
array('like', 'name', '%tester%')将会生成
name LIKE '%tester%'。如果operand 2是一个数组,那么将会生成多个LIKE判断值,这些判断值通过AND连接在一起。比如,array('like', 'name', array('%test%', '%sample%'))将会生成
name LIKE '%test%' AND name LIKE '%sample%'。该方法会正确的引用字段名并对IN范围值进行编码。
not like: 类似like。只不过对like的判断范围取反。
or like: 类似like,只不过当like的operand 2为一个数组时,连接该数组中的多个判断值的不是AND,而是OR。
or not like: 类似not like,只不过当like的operand 2为一个数组时,连接该数组中的多个判断值的不是AND,而是OR。
一下是使用where()的一些例子:
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">// WHERE id=1 or id=2 where('id=1 or id=2') // WHERE id=:id1 or id=:id2 where('id=:id1 or id=:id2', array(':id1'=>1, ':id2'=>2)) // WHERE id=1 OR id=2 where(array('or', 'id=1', 'id=2')) // WHERE id=1 AND (type=2 OR type=3) where(array('and', 'id=1', array('or', 'type=2', 'type=3'))) // WHERE `id` IN (1, 2) where(array('in', 'id', array(1, 2)) // WHERE `id` NOT IN (1, 2) where(array('not in', 'id', array(1,2))) // WHERE `name` LIKE '%Qiang%' where(array('like', 'name', '%Qiang%')) // WHERE `name` LIKE '%Qiang' AND `name` LIKE '%Xue' where(array('like', 'name', array('%Qiang', '%Xue'))) // WHERE `name` LIKE '%Qiang' OR `name` LIKE '%Xue' where(array('or like', 'name', array('%Qiang', '%Xue'))) // WHERE `name` NOT LIKE '%Qiang%' where(array('not like', 'name', '%Qiang%')) // WHERE `name` NOT LIKE '%Qiang%' OR `name` NOT LIKE '%Xue%' where(array('or not like', 'name', array('%Qiang%', '%Xue%')))</span></span>
注意,当操作符operand包含like的时候,我们必须明确的在operand 2中指定通配符(比如%和_)。如果operand 2的值来自如用户的输入,我们应该使用下面的代码对特殊字符进行编码,以免把用户输入的特殊字符,如%和_误认为是通配符:
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">$keyword=$_GET['q']; // escape % and _ characters $keyword=strtr($keyword, array('%'=>'\%', '_'=>'\_')); $command->where(array('like', 'title', '%'.$keyword.'%'));</span></span>
andWhere()
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">function andWhere($conditions, $params=array())</span></span>
andWhere()方法会将参数中的判断条件添加到WHERE部分,并与已有的WHERE判断条件使用AND操作符连接起来。该函数的用法基本上和where()一致,只不过该函数是向WHERE部分添加判断条件,而不是替换之前的判断条件。
orWhere()
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">function orWhere($conditions, $params=array())</span></span>
orWhere()方法会将参数中的判断条件添加到WHERE部分,并与已有的WHERE判断条件使用OR操作符连接起来。该函数的用法基本上和where()一致,只不过该函数是向WHERE部分添加判断条件,而不是替换之前的判断条件。
order()
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">function order($columns)</span></span>
order()函数指定了SELECT的ORDER BY部分。参数$columns可以是由逗号分隔开的多个字段以及排序方向(ASC或DESC)组成的字符串,也可以是包含多个字段和排序方向的数组。字段名可以包含表前缀。该方法会自动引入字段名,除非一个字段包含了一些插入符(说明该表是一个DB表达式或子查询)。
下面是一些例子:
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">// ORDER BY `name`, `id` DESC order('name, id desc') // ORDER BY `tbl_profile`.`name`, `id` DESC order(array('tbl_profile.name', 'id desc'))</span></span>
limit() 和 offset()
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">function limit($limit, $offset=null) function offset($offset)</span></span>
limit()和offset()函数指定了SELECT的LIMIT和OFFSET部分。
注意,一些DBMS可能不支持LIMIT和OFFSET语法,在这种情况下,查询助手会重写整个SQL语句来模拟limit和offset功能。
下面是一些例子:
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">// LIMIT 10 limit(10) // LIMIT 10 OFFSET 20 limit(10, 20) // OFFSET 20 offset(20)</span></span>
join()和相关变体
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">function join($table, $conditions, $params=array()) function leftJoin($table, $conditions, $params=array()) function rightJoin($table, $conditions, $params=array()) function crossJoin($table) function naturalJoin($table)</span></span>
join()方法和它的相关变体,指定了如何使用
INNER JOIN,
LEFT OUTER JOIN,
RIGHT OUTER JOIN,
CROSS JOIN,
NATURAL JOIN与其他表进行关联查询。
$table参数指定了关联哪张表。表名可以包含表前缀和/或别名。该方法会引入表名,除非它包含了插入符,这意味着它可能是一个DB表达式或子查询。
$conditions参数指定了关联条件,它的语法类似where()。
$params参数指定了绑定到整个查询中的参数值。
和其他查询助手方法不同,每个join方法调用都会被追加到之前的join中。
以下是一些例子:
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">// JOIN `tbl_profile` ON user_id=id join('tbl_profile', 'user_id=id') // LEFT JOIN `pub`.`tbl_profile` `p` ON p.user_id=id AND type=1 leftJoin('pub.tbl_profile p', 'p.user_id=id AND type=:type', array(':type'=>1))</span></span>
group()
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">function group($columns)</span></span>
group()函数指定了查询的GROUP BY部分。
$columns参数指定了进行分组的列。它既可以是使用逗号分开的多个字段组成的字符串,或者是一个包含多个字段的数组。字段名可以包含表前缀。
该方法会自动引入字段名,除非它包含了圆括弧,这意味着它可能是一个DB表达式。
下面是一些例子:
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">// GROUP BY `name`, `id` group('name, id') // GROUP BY `tbl_profile`.`name`, `id` group(array('tbl_profile.name', 'id'))</span></span>
having()
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">function having($conditions, $params=array())</span></span>
having()函数指定了查询的HAVING部分。它的使用方法类似where().
下面是一些实例:
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">// HAVING id=1 or id=2 having('id=1 or id=2') // HAVING id=1 OR id=2 having(array('or', 'id=1', 'id=2'))</span></span>
union()
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">function union($sql)</span></span>
union()函数指定了查询的UNION部分。它使用UNION操作符添加$sql到已有的SQL中。
调用union()函数多次,将会添加多个$sql到已存在的SQL中。
以下是一些例子:
<span style="font-family:Tahoma;font-size:12px;"><span style="font-size:12px;">// UNION (select * from tbl_profile) union('select * from tbl_profile')</span></span>
执行查询
在调用上面的查询助手创建了一个查询之后,我们就可以调用DAO方法执行查询了。举例来说,我们可以调用CDbCommand::queryRow()获取一条查询结果,或者调用CDbCommand::queryAll()获取全部执行结果。例如:<span style="font-family:Tahoma;font-size:12px;">$users = Yii::app()->db->createCommand() ->select('*') ->from('tbl_user') ->queryAll();</span>
获取SQL语句
除了执行一个由查询助手创建的查询操作,我们也可以重新获取相应的SQL语句,CDbCommand::getText()可以完成这个任务。<span style="font-family:Tahoma;font-size:12px;">$sql = Yii::app()->db->createCommand() ->select('*') ->from('tbl_user') ->text;</span>如果绑定了任何参数到一个查询操作上,我们可以通过CDbCommand::params来获取这些参数。
创建查询的替代语法
有时候,使用方法链来创建一个查询也许并不是最好的选择,Yii查询助手允许使用简单的对象属性赋值的方式来创建一个查询操作。特别是,对于每个查询助手方法,都有一个与该方法同名的属性。给属性赋值的方式,与调用相应的方法是一样的。举例来说,下面两个语句是同等的,如果$command指向了一个CDbCommand对象:<span style="font-family:Tahoma;font-size:12px;">$command->select(array('id', 'username')); $command->select = array('id', 'username');</span>此外,CDbConnection::createCommand()方法可以使用一个数组作为参数。数组中的键值对将被用来初始化创建的CDbCommand实例的属性。这意味着,我们可以使用如下代码创建一个查询:
<span style="font-family:Tahoma;font-size:12px;">$row = Yii::app()->db->createCommand(array( 'select' => array('id', 'username'), 'from' => 'tbl_user', 'where' => 'id=:id', 'params' => array(':id'=>1), ))->queryRow();</span>
创建多个查询
一个CDbCommand实例可以重复多次来使用创建多个查询。然而,在创建一个新的查询之前,需要调用CDbCommand::reset()方法来清除之前的查询。例如:<span style="font-family:Tahoma;font-size:12px;">$row = Yii::app()->db->createCommand(array( 'select' => array('id', 'username'), 'from' => 'tbl_user', 'where' => 'id=:id', 'params' => array(':id'=>1), ))->queryRow();</span>
3. 创建数据处理查询
数据处理查询指的是在一个数据库表中进行插入、更新和删除数据的SQL语句。相应这些查询操作,查询助手分别提供了insert, update和delete方法。
不同于上面描述的SELECT查询方法,每个数据处理查询方法,都为创建一个完整的SQL语句并且立即执行。
[insert()|CDbCommand::insert]: 在表中插入一行
[update()|CDbCommand::update]: 更新表中数据
[delete()|CDbCommand::delete]: 从表中删除数据
下面,我们一一介绍这些数据处理方法。
insert()
<span style="font-family:Tahoma;font-size:12px;">function insert($table, $columns)</span>
[insert()|CDbCommand::insert]方法创建并执行一条INSERT SQL语句。
$table参数指定了将数据插入哪张表,
$column参数,指定了要往表中插入的数据,以键值对数组的方式呈现。
下面是一个例子:
<span style="font-family:Tahoma;font-size:12px;">// build and execute the following SQL: // INSERT INTO `tbl_user` (`name`, `email`) VALUES (:name, :email) $command->insert('tbl_user', array( 'name'=>'Tester', 'email'=>'tester@example.com', ));</span>
update()
function update($table, $columns, $conditions='', $params=array())
update()方法创建并执行了一个UPDATE操作的SQL语句。
$table参数指定了要更新的表。
$column参数指定了用来更新字段值的键值对数组。
$condition和$param字段类似where()操作,指定UPDATE SQL语句的where部分。
该方法会引入表名,并且使用参数绑定要更新的数据。
下面是一个例子:
// build and execute the following SQL: // UPDATE `tbl_user` SET `name`=:name WHERE id=:id $command->update('tbl_user', array( 'name'=>'Tester', ), 'id=:id', array(':id'=>1));
delete()
function delete($table, $conditions='', $params=array())
delete()方法创建并执行了一个DELETE操作的SQL语句。
$table参数指定了要从哪张表里删除数据。
$condition和$param字段类似where()操作,指定DELETE SQL语句的where部分。
该方法会引入表名。
下面是一个例子:
// build and execute the following SQL: // DELETE FROM `tbl_user` WHERE id=:id $command->delete('tbl_user', 'id=:id', array(':id'=>1));
4. 数据库对象操作
译者注:和上面我们讲的不同的是,上面的操作都是针对表里面的数据的。而数据库对象操作是针对表一级的操作的,比如,创建、删除、修改、清除表等。而这些操作对数据库和整个系统的影响非常大,如果操作不善,有可能对整个系统带来灾难性的事故,甚至酿成不可恢复的重大影响。因此,对于数据库级别和表级别的操作,建议还是尽量由DBA通过DBMS手动操作。因此,本章的内容就不翻译了,但是会贴入原文。事实上,上面的翻译已经差不多囊括了查询助手篇的所有专业名词的翻译,以及参数形式、意义的讲解和使用方法。Besides normal data retrieval and manipulation queries, the query builder also offers a set of methods for building and executing SQL queries that can manipulate the schema of a database. In particular, it supports the following queries:
createTable():
creates a table
renameTable():
renames a table
dropTable(): drops
a table
truncateTable():
truncates a table
addColumn(): adds
a table column
renameColumn():
renames a table column
alterColumn():
alters a table column
addForeignKey():
adds a foreign key (available since 1.1.6)
dropForeignKey():
drops a foreign key (available since 1.1.6)
dropColumn(): drops
a table column
createIndex():
creates an index
dropIndex(): drops
an index
Info: Although the actual SQL statements for manipulating database schema vary widely across different DBMS, the query builder attempts to
provide a uniform interface for building these queries. This simplifies the task of migrating a database from one DBMS to another.
Abstract Data Types
The query builder introduces a set of abstract data types that can be used in defining table columns. Unlike the physical data types that are specific to particular DBMS and are quite different in different DBMS, the abstract data types are independent of DBMS.When abstract data types are used in defining table columns, the query builder will convert them into the corresponding physical data types.
The following abstract data types are supported by the query builder.
pk:
a generic primary key type, will be converted into
int(11) NOT NULL AUTO_INCREMENT PRIMARY KEYfor MySQL;
string:
string type, will be converted into
varchar(255)for
MySQL;
text:
text type (long string), will be converted into
textfor
MySQL;
integer:
integer type, will be converted into
int(11)for
MySQL;
float:
floating number type, will be converted into
floatfor
MySQL;
decimal:
decimal number type, will be converted into
decimalfor
MySQL;
datetime:
datetime type, will be converted into
datetimefor
MySQL;
timestamp:
timestamp type, will be converted into
timestampfor
MySQL;
time:
time type, will be converted into
timefor
MySQL;
date:
date type, will be converted into
datefor
MySQL;
binary:
binary data type, will be converted into
blobfor
MySQL;
boolean:
boolean type, will be converted into
tinyint(1)for
MySQL;
money:
money/currency type, will be converted into
decimal(19,4)for
MySQL. This type has been available since version 1.1.8.
createTable()
function createTable($table, $columns, $options=null)
The createTable() method
builds and executes a SQL statement for creating a table. The
$tableparameter
specifies the name of the table to be created. The
$columnsparameter
specifies the columns in the new table. They must be given as name-definition pairs (e.g.
'username'=>'string').
The
$optionsparameter
specifies any extra SQL fragment that should be appended to the generated SQL. The query builder will quote the table name as well as the column names properly.
When specifying a column definition, one can use an abstract data type as described above. The query builder will convert the abstract data type into the corresponding physical data type, according to the currently used DBMS. For example,
stringwill
be converted into
varchar(255)for
MySQL.
A column definition can also contain non-abstract data type or specifications. They will be put in the generated SQL without any change. For example,
pointis
not an abstract data type, and if used in a column definition, it will appear as is in the resulting SQL; and
string NOT NULLwill be converted into
varchar(255) NOT NULL(i.e., only the abstract type
stringis
converted).
Below is an example showing how to create a table:
// CREATE TABLE `tbl_user` ( // `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, // `username` varchar(255) NOT NULL, // `location` point // ) ENGINE=InnoDB createTable('tbl_user', array( 'id' => 'pk', 'username' => 'string NOT NULL', 'location' => 'point', ), 'ENGINE=InnoDB')
renameTable()
function renameTable($table, $newName)
The renameTable() method
builds and executes a SQL statement for renaming a table. The
$tableparameter
specifies the name of the table to be renamed. The
$newNameparameter
specifies the new name of the table. The query builder will quote the table names properly.
Below is an example showing how to rename a table:
// RENAME TABLE `tbl_users` TO `tbl_user` renameTable('tbl_users', 'tbl_user')
dropTable()
function dropTable($table)
The dropTable() method
builds and executes a SQL statement for dropping a table. The
$tableparameter
specifies the name of the table to be dropped. The query builder will quote the table name properly.
Below is an example showing how to drop a table:
// DROP TABLE `tbl_user` dropTable('tbl_user')
truncateTable()
function truncateTable($table)
The truncateTable() method
builds and executes a SQL statement for truncating a table. The
$tableparameter
specifies the name of the table to be truncated. The query builder will quote the table name properly.
Below is an example showing how to truncate a table:
// TRUNCATE TABLE `tbl_user` truncateTable('tbl_user')
addColumn()
function addColumn($table, $column, $type)
The addColumn() method
builds and executes a SQL statement for adding a new table column. The
$tableparameter
specifies the name of the table that the new column will be added to. The
$columnparameter
specifies the name of the new column. And
$typespecifies
the definition of the new column. Column definition can contain abstract data type, as described in the subsection of "createTable". The query builder will quote the table name as well as the column name properly.
Below is an example showing how to add a table column:
// ALTER TABLE `tbl_user` ADD `email` varchar(255) NOT NULL addColumn('tbl_user', 'email', 'string NOT NULL')
dropColumn()
function dropColumn($table, $column)
The dropColumn() method
builds and executes a SQL statement for dropping a table column. The
$tableparameter
specifies the name of the table whose column is to be dropped. The
$columnparameter
specifies the name of the column to be dropped. The query builder will quote the table name as well as the column name properly.
Below is an example showing how to drop a table column:
// ALTER TABLE `tbl_user` DROP COLUMN `location` dropColumn('tbl_user', 'location')
renameColumn()
function renameColumn($table, $name, $newName)
The renameColumn() method
builds and executes a SQL statement for renaming a table column. The
$tableparameter
specifies the name of the table whose column is to be renamed. The
$nameparameter
specifies the old column name. And
$newNamespecifies
the new column name. The query builder will quote the table name as well as the column names properly.
Below is an example showing how to rename a table column:
// ALTER TABLE `tbl_users` CHANGE `name` `username` varchar(255) NOT NULL renameColumn('tbl_user', 'name', 'username')
alterColumn()
function alterColumn($table, $column, $type)
The alterColumn() method
builds and executes a SQL statement for altering a table column. The
$tableparameter
specifies the name of the table whose column is to be altered. The
$columnparameter
specifies the name of the column to be altered. And
$typespecifies
the new definition of the column. Column definition can contain abstract data type, as described in the subsection of "createTable". The query builder will quote the table name as well as the column name properly.
Below is an example showing how to alter a table column:
// ALTER TABLE `tbl_user` CHANGE `username` `username` varchar(255) NOT NULL alterColumn('tbl_user', 'username', 'string NOT NULL')
addForeignKey()
function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
The addForeignKey() method
builds and executes a SQL statement for adding a foreign key constraint to a table. The
$nameparameter
specifies the name of the foreign key. The
$tableand
$columnsparameters
specify the table name and column name that the foreign key is about. If there are multiple columns, they should be separated by comma characters. The
$refTableand
$refColumnsparameters
specify the table name and column name that the foreign key references. The
$deleteand
$updateparameters
specify the
ON DELETEand
ON UPDATEoptions in the SQL statement, respectively. Most DBMS support these options:
RESTRICT,
CASCADE,
NO ACTION,
SET DEFAULT,
SET NULL. The query builder will properly quote the table name, index name and column name(s).
Below is an example showing how to add a foreign key constraint,
// ALTER TABLE `tbl_profile` ADD CONSTRAINT `fk_profile_user_id` // FOREIGN KEY (`user_id`) REFERENCES `tbl_user` (`id`) // ON DELETE CASCADE ON UPDATE CASCADE addForeignKey('fk_profile_user_id', 'tbl_profile', 'user_id', 'tbl_user', 'id', 'CASCADE', 'CASCADE')
dropForeignKey()
function dropForeignKey($name, $table)
The dropForeignKey() method
builds and executes a SQL statement for dropping a foreign key constraint. The
$nameparameter
specifies the name of the foreign key constraint to be dropped. The
$tableparameter
specifies the name of the table that the foreign key is on. The query builder will quote the table name as well as the constraint names properly.
Below is an example showing how to drop a foreign key constraint:
// ALTER TABLE `tbl_profile` DROP FOREIGN KEY `fk_profile_user_id` dropForeignKey('fk_profile_user_id', 'tbl_profile')
createIndex()
function createIndex($name, $table, $column, $unique=false)
The createIndex() method
builds and executes a SQL statement for creating an index. The
$nameparameter
specifies the name of the index to be created. The
$tableparameter
specifies the name of the table that the index is on. The
$columnparameter
specifies the name of the column to be indexed. And the
$uniqueparameter
specifies whether a unique index should be created. If the index consists of multiple columns, they must be separated by commas. The query builder will properly quote the table name, index name and column name(s).
Below is an example showing how to create an index:
// CREATE INDEX `idx_username` ON `tbl_user` (`username`) createIndex('idx_username', 'tbl_user', 'username')
dropIndex()
function dropIndex($name, $table)
The dropIndex() method
builds and executes a SQL statement for dropping an index. The
$nameparameter
specifies the name of the index to be dropped. The
$tableparameter
specifies the name of the table that the index is on. The query builder will quote the table name as well as the index names properly.
Below is an example showing how to drop an index:
// DROP INDEX `idx_username` ON `tbl_user` dropIndex('idx_username', 'tbl_user')
相关文章推荐
- GNS3 1.4.0b3 MSTP多生成树配置实验
- php手册之Trait
- php的错误和异常处理
- PHP获取下个月的1月1日,唯一要解决的其实就是跨年的问题
- php.ini文件中关于cookie和session的设置
- php 使用session保存页面登录信息
- PHP Session 登陆 验证
- Zend不支持php5.3、不支持Windows下非线程安全PHPFastCGI
- PHP设计模式一:工厂方法设计模式
- PHP中each与数组变量分离的那些事情
- php 常用函数
- 国内常用NTP服务器地址及IP
- php 框架
- 算法杂项
- php数字每三位加逗号的功能函数
- php之文件上传
- Yii2分页
- [php] thinkphp实现 163 qq 邮箱收发邮件(切实可用)
- 通过smtp协议简单实现邮件发送
- Thinlphp 模版 foreach 嵌套在 另一个循环出现不能在次循环问题。