数据库抽象层Database Abstraction Layer

Phalcon\DbPhalcon\Mvc\Model 背后的一个组件,它为框架提供了强大的model层。它是一个完全由C语言写的独立的高级抽象层的数据库系统。

Phalcon\Db is the component behind Phalcon\Mvc\Model that powers the model layer in the framework. It consists of an independent high-level abstraction layer for database systems completely written in C.

这个组件提供了比传统模式的更容易上手的数据库操作。

This component allows for a lower level database manipulation than using traditional models.

这个指引不是一个完整的包含所有方法和它们的参数的文档。 查看完整的文档参考,请访问 API

This guide is not intended to be a complete documentation of available methods and their arguments. Please visit the API for a complete reference.

数据库适配器Database Adapters

这个组件利用了这些适配器去封装特定的数据库的详细操作。Phalcon使用 PDO 去连接这些数据库。下面这些是我们支持的数据库引擎:

This component makes use of adapters to encapsulate specific database system details. Phalcon uses PDO to connect to databases. The following database engines are supported:

NameDescriptionAPI
MySQLIs the world’s most used relational database management system (RDBMS) that runs as a server providing multi-user access to a number of databasesPhalcon\Db\Adapter\Pdo\Mysql
PostgreSQLPostgreSQL is a powerful, open source relational database system. It has more than 15 years of active development and a proven architecture that has earned it a strong reputation for reliability, data integrity, and correctness.Phalcon\Db\Adapter\Pdo\Postgresql
SQLiteSQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database enginePhalcon\Db\Adapter\Pdo\Sqlite
OracleOracle is an object-relational database management system produced and marketed by Oracle Corporation.Phalcon\Db\Adapter\Pdo\Oracle

自定义适配器Implementing your own adapters

如果你想创建自己的适配器或者扩展现有的适配器,这个 Phalcon\Db\AdapterInterface 接口必须被实现。

The Phalcon\Db\AdapterInterface interface must be implemented in order to create your own database adapters or extend the existing ones.

数据库“接口”封装Database Dialects

Phalcon把每个数据库引擎的具体操作封装成“接口”,这些“接口”提供了提供通用的功能和SQL生成的适配器。 (译者注:这里的“接口”是指Phalcon把一些常用的数据库操作封装成类的方法,例如检查数据库中表是否存在,不再需要麻烦的手动写SQL,可以把调用tableExists方法去查询)

Phalcon encapsulates the specific details of each database engine in dialects. Those provide common functions and SQL generator to the adapters.

NameDescriptionAPI
MySQLSQL specific dialect for MySQL database systemPhalcon\Db\Dialect\Mysql
PostgreSQLSQL specific dialect for PostgreSQL database systemPhalcon\Db\Dialect\Postgresql
SQLiteSQL specific dialect for SQLite database systemPhalcon\Db\Dialect\Sqlite
OracleSQL specific dialect for Oracle database systemPhalcon\Db\Dialect\Oracle

自定义“接口”Implementing your own dialects

如果你想创建自己的“接口”或者扩展现有的“接口”,你需要实现这个接口:Phalcon\Db\DialectInterface

The Phalcon\Db\DialectInterface interface must be implemented in order to create your own database dialects or extend the existing ones.

连接数据库Connecting to Databases

为了建立连接,实例化适配器类是必须的。它只接收一个包含连接参数的数组。 下面的例子展示了,传递必要参数和可选项的参数去连接数据库:

To create a connection it’s necessary instantiate the adapter class. It only requires an array with the connection parameters. The example below shows how to create a connection passing both required and optional parameters:

  1. <?php
  2. // Required
  3. $config = array(
  4. "host" => "127.0.0.1",
  5. "username" => "mike",
  6. "password" => "sigma",
  7. "dbname" => "test_db"
  8. );
  9. // Optional
  10. $config["persistent"] = false;
  11. // Create a connection
  12. $connection = new \Phalcon\Db\Adapter\Pdo\Mysql($config);
  1. <?php
  2. // Required
  3. $config = array(
  4. "host" => "localhost",
  5. "username" => "postgres",
  6. "password" => "secret1",
  7. "dbname" => "template"
  8. );
  9. // Optional
  10. $config["schema"] = "public";
  11. // Create a connection
  12. $connection = new \Phalcon\Db\Adapter\Pdo\Postgresql($config);
  1. <?php
  2. // Required
  3. $config = array(
  4. "dbname" => "/path/to/database.db"
  5. );
  6. // Create a connection
  7. $connection = new \Phalcon\Db\Adapter\Pdo\Sqlite($config);
  1. <?php
  2. // Basic configuration
  3. $config = array(
  4. 'username' => 'scott',
  5. 'password' => 'tiger',
  6. 'dbname' => '192.168.10.145/orcl',
  7. );
  8. // Advanced configuration
  9. $config = array(
  10. 'dbname' => '(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=xe)(FAILOVER_MODE=(TYPE=SELECT)(METHOD=BASIC)(RETRIES=20)(DELAY=5))))',
  11. 'username' => 'scott',
  12. 'password' => 'tiger',
  13. 'charset' => 'AL32UTF8',
  14. );
  15. // Create a connection
  16. $connection = new \Phalcon\Db\Adapter\Pdo\Oracle($config);

设置额外的 PDO 选项Setting up additional PDO options

你可以在连接的时候,通过传递’options’参数,设置PDO选项:

You can set PDO options at connection time by passing the parameters ‘options’:

  1. <?php
  2. // Create a connection with PDO options
  3. $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array(
  4. "host" => "localhost",
  5. "username" => "root",
  6. "password" => "sigma",
  7. "dbname" => "test_db",
  8. "options" => array(
  9. PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES \'UTF8\'",
  10. PDO::ATTR_CASE => PDO::CASE_LOWER
  11. )
  12. ));

查找行Finding Rows

Phalcon\Db 提供了几种方法去查询行。在这个例子中,SQL语句是必须符合数据库的SQL语法的:

Phalcon\Db provides several methods to query rows from tables. The specific SQL syntax of the target database engine is required in this case:

  1. <?php
  2. $sql = "SELECT id, name FROM robots ORDER BY name";
  3. // Send a SQL statement to the database system
  4. $result = $connection->query($sql);
  5. // Print each robot name
  6. while ($robot = $result->fetch()) {
  7. echo $robot["name"];
  8. }
  9. // Get all rows in an array
  10. $robots = $connection->fetchAll($sql);
  11. foreach ($robots as $robot) {
  12. echo $robot["name"];
  13. }
  14. // Get only the first row
  15. $robot = $connection->fetchOne($sql);

默认情况下,这些调用会建立一个数组,数组中包含以字段名和以数字下标为key的值。你可以改变这种行为通过使用 Phalcon\Db\Result::setFetchMode() 。这个方法接受一个常量值,确定哪些类型的指标是被要求的。

By default these calls create arrays with both associative and numeric indexes. You can change this behavior by using Phalcon\Db\Result::setFetchMode(). This method receives a constant, defining which kind of index is required.

ConstantDescription
Phalcon\Db::FETCH_NUMReturn an array with numeric indexes
Phalcon\Db::FETCH_ASSOCReturn an array with associative indexes
Phalcon\Db::FETCH_BOTHReturn an array with both associative and numeric indexes
Phalcon\Db::FETCH_OBJReturn an object instead of an array
  1. <?php
  2. $sql = "SELECT id, name FROM robots ORDER BY name";
  3. $result = $connection->query($sql);
  4. $result->setFetchMode(Phalcon\Db::FETCH_NUM);
  5. while ($robot = $result->fetch()) {
  6. echo $robot[0];
  7. }

这个 Phalcon\Db::query() 方法返回一个 :doc:`Phalcon\Db\Result\Pdo <../api/Phalcon_Db_Result_Pdo>`实例。这些对象封装了凡是涉及到返回的结果集的功能,例如遍历,寻找特定行,计算总行数等等

The Phalcon\Db::query() returns an instance of Phalcon\Db\Result\Pdo. These objects encapsulate all the functionality related to the returned resultset i.e. traversing, seeking specific records, count etc.

  1. <?php
  2. $sql = "SELECT id, name FROM robots";
  3. $result = $connection->query($sql);
  4. // Traverse the resultset
  5. while ($robot = $result->fetch()) {
  6. echo $robot["name"];
  7. }
  8. // Seek to the third row
  9. $result->seek(2);
  10. $robot = $result->fetch();
  11. // Count the resultset
  12. echo $result->numRows();

绑定参数Binding Parameters

Phalcon\Db 中支持绑定参数。虽然使用绑定参数会有很少性能的损失,但是我们鼓励你使用这个方法 去消除(译者注:是消除,不是减少,因为使用参数绑定可以彻底解决SQL注入问题)SQL注入攻击的可能性。 字符串和占位符都支持,就像下面展示的那样,绑定参数可以简单地实现:

Bound parameters is also supported in Phalcon\Db. Although there is a minimal performance impact by using bound parameters, you are encouraged to use this methodology so as to eliminate the possibility of your code being subject to SQL injection attacks. Both string and positional placeholders are supported. Binding parameters can simply be achieved as follows:

  1. <?php
  2. // Binding with numeric placeholders
  3. $sql = "SELECT * FROM robots WHERE name = ? ORDER BY name";
  4. $result = $connection->query($sql, array("Wall-E"));
  5. // Binding with named placeholders
  6. $sql = "INSERT INTO `robots`(name`, year) VALUES (:name, :year)";
  7. $success = $connection->query($sql, array("name" => "Astro Boy", "year" => 1952));

插入、更新、删除行Inserting/Updating/Deleting Rows

去插入,更新或者删除行,你可以使用原生SQL操作,或者使用类中预设的方法

To insert, update or delete rows, you can use raw SQL or use the preset functions provided by the class:

  1. <?php
  2. // Inserting data with a raw SQL statement
  3. $sql = "INSERT INTO `robots`(`name`, `year`) VALUES ('Astro Boy', 1952)";
  4. $success = $connection->execute($sql);
  5. //With placeholders
  6. $sql = "INSERT INTO `robots`(`name`, `year`) VALUES (?, ?)";
  7. $success = $connection->execute($sql, array('Astro Boy', 1952));
  8. // Generating dynamically the necessary SQL
  9. $success = $connection->insert(
  10. "robots",
  11. array("Astro Boy", 1952),
  12. array("name", "year")
  13. );
  14. // Generating dynamically the necessary SQL (another syntax)
  15. $success = $connection->insertAsDict(
  16. "robots",
  17. array(
  18. "name" => "Astro Boy",
  19. "year" => 1952
  20. )
  21. );
  22. // Updating data with a raw SQL statement
  23. $sql = "UPDATE `robots` SET `name` = 'Astro boy' WHERE `id` = 101";
  24. $success = $connection->execute($sql);
  25. //With placeholders
  26. $sql = "UPDATE `robots` SET `name` = ? WHERE `id` = ?";
  27. $success = $connection->execute($sql, array('Astro Boy', 101));
  28. // Generating dynamically the necessary SQL
  29. $success = $connection->update(
  30. "robots",
  31. array("name"),
  32. array("New Astro Boy"),
  33. "id = 101" //Warning! In this case values are not escaped
  34. );
  35. // Generating dynamically the necessary SQL (another syntax)
  36. $success = $connection->updateAsDict(
  37. "robots",
  38. array(
  39. "name" => "New Astro Boy"
  40. ),
  41. "id = 101" //Warning! In this case values are not escaped
  42. );
  43. //With escaping conditions
  44. $success = $connection->update(
  45. "robots",
  46. array("name"),
  47. array("New Astro Boy"),
  48. array(
  49. 'conditions' => 'id = ?',
  50. 'bind' => array(101),
  51. 'bindTypes' => array(PDO::PARAM_INT) //optional parameter
  52. )
  53. );
  54. $success = $connection->updateAsDict(
  55. "robots",
  56. array(
  57. "name" => "New Astro Boy"
  58. ),
  59. array(
  60. 'conditions' => 'id = ?',
  61. 'bind' => array(101),
  62. 'bindTypes' => array(PDO::PARAM_INT) //optional parameter
  63. )
  64. );
  65. // Deleting data with a raw SQL statement
  66. $sql = "DELETE `robots` WHERE `id` = 101";
  67. $success = $connection->execute($sql);
  68. //With placeholders
  69. $sql = "DELETE `robots` WHERE `id` = ?";
  70. $success = $connection->execute($sql, array(101));
  71. // Generating dynamically the necessary SQL
  72. $success = $connection->delete("robots", "id = ?", array(101));

事务与嵌套事务Transactions and Nested Transactions

PDO支持事务工作。在事务里面执行数据操作, 在大多数数据库系统上, 往往可以提高数据库的性能:

Working with transactions is supported as it is with PDO. Perform data manipulation inside transactions often increase the performance on most database systems:

  1. <?php
  2. try {
  3. //Start a transaction
  4. $connection->begin();
  5. //Execute some SQL statements
  6. $connection->execute("DELETE `robots` WHERE `id` = 101");
  7. $connection->execute("DELETE `robots` WHERE `id` = 102");
  8. $connection->execute("DELETE `robots` WHERE `id` = 103");
  9. //Commit if everything goes well
  10. $connection->commit();
  11. } catch(Exception $e) {
  12. //An exception has occurred rollback the transaction
  13. $connection->rollback();
  14. }

除了标准的事务,Phalcon\Db提供了内置支持 `nested transactions`_(如果数据库系统支持的话)。 当你第二次调用begin()方法,一个嵌套的事务就被创建了:

In addition to standard transactions, Phalcon\Db provides built-in support for nested transactions (if the database system used supports them). When you call begin() for a second time a nested transaction is created:

  1. <?php
  2. try {
  3. //Start a transaction
  4. $connection->begin();
  5. //Execute some SQL statements
  6. $connection->execute("DELETE `robots` WHERE `id` = 101");
  7. try {
  8. //Start a nested transaction
  9. $connection->begin();
  10. //Execute these SQL statements into the nested transaction
  11. $connection->execute("DELETE `robots` WHERE `id` = 102");
  12. $connection->execute("DELETE `robots` WHERE `id` = 103");
  13. //Create a save point
  14. $connection->commit();
  15. } catch(Exception $e) {
  16. //An error has occurred, release the nested transaction
  17. $connection->rollback();
  18. }
  19. //Continue, executing more SQL statements
  20. $connection->execute("DELETE `robots` WHERE `id` = 104");
  21. //Commit if everything goes well
  22. $connection->commit();
  23. } catch(Exception $e) {
  24. //An exception has occurred rollback the transaction
  25. $connection->rollback();
  26. }

数据库事件Database Events

Phalcon\Db 可以发送事件到一个 EventsManager 中,如果它存在的话。 一些事件当返回布尔值false可以停止操作。我们支持下面这些事件:

Phalcon\Db is able to send events to a EventsManager if it’s present. Some events when returning boolean false could stop the active operation. The following events are supported:

Event NameTriggeredCan stop operation?
afterConnectAfter a successfully connection to a database systemNo
beforeQueryBefore send a SQL statement to the database systemYes
afterQueryAfter send a SQL statement to database systemNo
beforeDisconnectBefore close a temporal database connectionNo
beginTransactionBefore a transaction is going to be startedNo
rollbackTransactionBefore a transaction is rollbackedNo
commitTransactionBefore a transaction is committed | No

绑定一个EventsManager给一个连接是很简单的, Phalcon\Db 将触发这些类型为“db”的事件:

Bind an EventsManager to a connection is simple, Phalcon\Db will trigger the events with the type “db”:

  1. <?php
  2. use Phalcon\Events\Manager as EventsManager,
  3. \Phalcon\Db\Adapter\Pdo\Mysql as Connection;
  4. $eventsManager = new EventsManager();
  5. //Listen all the database events
  6. $eventsManager->attach('db', $dbListener);
  7. $connection = new Connection(array(
  8. "host" => "localhost",
  9. "username" => "root",
  10. "password" => "secret",
  11. "dbname" => "invo"
  12. ));
  13. //Assign the eventsManager to the db adapter instance
  14. $connection->setEventsManager($eventsManager);

数据库事件中,停止操作是非常有用的,例如:如果你想要实现一个注入检查器,在发送SQL到数据库前触发:

Stop SQL operations are very useful if for example you want to implement some last-resource SQL injector checker:

  1. <?php
  2. $eventsManager->attach('db:beforeQuery', function($event, $connection) {
  3. //Check for malicious words in SQL statements
  4. if (preg_match('/DROP|ALTER/i', $connection->getSQLStatement())) {
  5. // DROP/ALTER operations aren't allowed in the application,
  6. // this must be a SQL injection!
  7. return false;
  8. }
  9. //It's ok
  10. return true;
  11. });

分析 SQL 语句Profiling SQL Statements

Phalcon\Db,它被用于分析数据库的操作性能以便诊断性能问题,并发现瓶颈。 使用 doc:Phalcon\Db\Profiler <../api/Phalcon_Db_Profiler> 来分析数据库真的很简单:

Phalcon\Db includes a profiling component called Phalcon\Db\Profiler, that is used to analyze the performance of database operations so as to diagnose performance problems and discover bottlenecks.

Database profiling is really easy With Phalcon\Db\Profiler:

  1. <?php
  2. use Phalcon\Events\Manager as EventsManager,
  3. Phalcon\Db\Profiler as DbProfiler;
  4. $eventsManager = new EventsManager();
  5. $profiler = new DbProfiler();
  6. //Listen all the database events
  7. $eventsManager->attach('db', function($event, $connection) use ($profiler) {
  8. if ($event->getType() == 'beforeQuery') {
  9. //Start a profile with the active connection
  10. $profiler->startProfile($connection->getSQLStatement());
  11. }
  12. if ($event->getType() == 'afterQuery') {
  13. //Stop the active profile
  14. $profiler->stopProfile();
  15. }
  16. });
  17. //Assign the events manager to the connection
  18. $connection->setEventsManager($eventsManager);
  19. $sql = "SELECT buyer_name, quantity, product_name "
  20. . "FROM buyers "
  21. . "LEFT JOIN products ON buyers.pid = products.id";
  22. // Execute a SQL statement
  23. $connection->query($sql);
  24. // Get the last profile in the profiler
  25. $profile = $profiler->getLastProfile();
  26. echo "SQL Statement: ", $profile->getSQLStatement(), "\n";
  27. echo "Start Time: ", $profile->getInitialTime(), "\n";
  28. echo "Final Time: ", $profile->getFinalTime(), "\n";
  29. echo "Total Elapsed Time: ", $profile->getTotalElapsedSeconds(), "\n";

你也可以基于 Phalcon\Db\Profiler 建立你自己的分析器类,以记录SQL语句发送到数据库的实时统计:

You can also create your own profile class based on Phalcon\Db\Profiler to record real time statistics of the statements sent to the database system:

  1. <?php
  2. use Phalcon\Events\Manager as EventsManager,
  3. Phalcon\Db\Profiler as Profiler,
  4. Phalcon\Db\Profiler\Item as Item;
  5. class DbProfiler extends Profiler
  6. {
  7. /**
  8. * Executed before the SQL statement will sent to the db server
  9. */
  10. public function beforeStartProfile(Item $profile)
  11. {
  12. echo $profile->getSQLStatement();
  13. }
  14. /**
  15. * Executed after the SQL statement was sent to the db server
  16. */
  17. public function afterEndProfile(Item $profile)
  18. {
  19. echo $profile->getTotalElapsedSeconds();
  20. }
  21. }
  22. //Create an EventsManager
  23. $eventsManager = new EventsManager();
  24. //Create a listener
  25. $dbProfiler = new DbProfiler();
  26. //Attach the listener listening for all database events
  27. $eventsManager->attach('db', $dbProfiler);

记录 SQL 语句Logging SQL Statements

使用例如 Phalcon\Db 的高级抽象组件操作数据库,被发送到数据库中执行的原生SQL语句是难以获知的。使用 Phalcon\LoggerPhalcon\Db 来配合使用,可以在数据库抽象层上提供记录的功能。

Using high-level abstraction components such as Phalcon\Db to access a database, it is difficult to understand which statements are sent to the database system. Phalcon\Logger interacts with Phalcon\Db, providing logging capabilities on the database abstraction layer.

  1. <?php
  2. use Phalcon\Logger,
  3. Phalcon\Events\Manager as EventsManager,
  4. Phalcon\Logger\Adapter\File as FileLogger;
  5. $eventsManager = new EventsManager();
  6. $logger = new FileLogger("app/logs/db.log");
  7. //Listen all the database events
  8. $eventsManager->attach('db', function($event, $connection) use ($logger) {
  9. if ($event->getType() == 'beforeQuery') {
  10. $logger->log($connection->getSQLStatement(), Logger::INFO);
  11. }
  12. });
  13. //Assign the eventsManager to the db adapter instance
  14. $connection->setEventsManager($eventsManager);
  15. //Execute some SQL statement
  16. $connection->insert(
  17. "products",
  18. array("Hot pepper", 3.50),
  19. array("name", "price")
  20. );

如上操作,文件 app/logs/db.log 将包含像下面这样的信息:

As above, the file app/logs/db.log will contain something like this:

  1. [Sun, 29 Apr 12 22:35:26 -0500][DEBUG][Resource Id #77] INSERT INTO products
  2. (name, price) VALUES ('Hot pepper', 3.50)

自定义日志记录器Implementing your own Logger

你可以实现你自己的日志类来记录数据库的所有操作,通过创建一个实现了”log”方法的类。 这个方法需要接受一个字符串作为第一个参数。你可以把日志类的对象传递给Phalcon\Db::setLogger(), 这样执行SQL时将调用这个对象的log方法去记录。

You can implement your own logger class for database queries, by creating a class that implements a single method called “log”. The method needs to accept a string as the first argument. You can then pass your logging object to Phalcon\Db::setLogger(), and from then on any SQL statement executed will call that method to log the results.

获取数据库表与视图信息Describing Tables/Views

PhalconDb 也提供了方法去检索详细的表和视图信息:

Phalcon\Db also provides methods to retrieve detailed information about tables and views:

  1. <?php
  2. // Get tables on the test_db database
  3. $tables = $connection->listTables("test_db");
  4. // Is there a table 'robots' in the database?
  5. $exists = $connection->tableExists("robots");
  6. // Get name, data types and special features of 'robots' fields
  7. $fields = $connection->describeColumns("robots");
  8. foreach ($fields as $field) {
  9. echo "Column Type: ", $field["Type"];
  10. }
  11. // Get indexes on the 'robots' table
  12. $indexes = $connection->describeIndexes("robots");
  13. foreach ($indexes as $index) {
  14. print_r($index->getColumns());
  15. }
  16. // Get foreign keys on the 'robots' table
  17. $references = $connection->describeReferences("robots");
  18. foreach ($references as $reference) {
  19. // Print referenced columns
  20. print_r($reference->getReferencedColumns());
  21. }

一个表的详细描述信息和MYSQL的describe命令返回的信息非常相似,它包含以下信息:

A table description is very similar to the MySQL describe command, it contains the following information:

IndexDescription
FieldField’s name
TypeColumn Type
KeyIs the column part of the primary key or an index?
NullDoes the column allow null values?

对于被支持的数据库系统,获取视图的信息的方法也被实现了:

Methods to get information about views are also implemented for every supported database system:

  1. <?php
  2. // Get views on the test_db database
  3. $tables = $connection->listViews("test_db");
  4. // Is there a view 'robots' in the database?
  5. $exists = $connection->viewExists("robots");

创建/修改/删除表Creating/Altering/Dropping Tables

不同的数据库系统(MySQL,Postgresql等)通过了CREATE, ALTER 或 DROP命令提供了用于创建,修改或删除表的功能。但是不同的数据库语法不同。 Phalcon\Db 提供了统一的接口来改变表,而不需要区分基于目标存储系统上的SQL语法。

Different database systems (MySQL, Postgresql etc.) offer the ability to create, alter or drop tables with the use of commands such as CREATE, ALTER or DROP. The SQL syntax differs based on which database system is used. Phalcon\Db offers a unified interface to alter tables, without the need to differentiate the SQL syntax based on the target storage system.

创建数据库表Creating Tables

下面这个例子展示了怎么建立一个表:

The following example shows how to create a table:

  1. <?php
  2. use \Phalcon\Db\Column as Column;
  3. $connection->createTable(
  4. "robots",
  5. null,
  6. array(
  7. "columns" => array(
  8. new Column("id",
  9. array(
  10. "type" => Column::TYPE_INTEGER,
  11. "size" => 10,
  12. "notNull" => true,
  13. "autoIncrement" => true,
  14. )
  15. ),
  16. new Column("name",
  17. array(
  18. "type" => Column::TYPE_VARCHAR,
  19. "size" => 70,
  20. "notNull" => true,
  21. )
  22. ),
  23. new Column("year",
  24. array(
  25. "type" => Column::TYPE_INTEGER,
  26. "size" => 11,
  27. "notNull" => true,
  28. )
  29. )
  30. )
  31. )
  32. );

Phalcon\Db::createTable()接受一个描述数据库表相关的数组。字段被定义成class Phalcon\Db\Column 。 下表列出了可用于定义字段的选项:

Phalcon\Db::createTable() accepts an associative array describing the table. Columns are defined with the class Phalcon\Db\Column. The table below shows the options available to define a column:

OptionDescriptionOptional
“type”Column type. Must be a Phalcon\Db\Column constant (see below for a list)No
“primary”True if the column is part of the table’s primaryYes
“size”Some type of columns like VARCHAR or INTEGER may have a specific sizeYes
“scale”DECIMAL or NUMBER columns may be have a scale to specify how many decimals should be storedYes
“unsigned”INTEGER columns may be signed or unsigned. This option does not apply to other types of columnsYes
“notNull”Column can store null values?Yes
“autoIncrement”With this attribute column will filled automatically with an auto-increment integer. Only one column in the table can have this attribute.Yes
“bind”One of the BINDTYPE* constants telling how the column must be binded before save itYes
“first”Column must be placed at first position in the column orderYes
“after”Column must be placed after indicated columnYes

PhalconDb 支持下面的数据库字段类型:

Phalcon\Db supports the following database column types:

  • Phalcon\Db\Column::TYPE_INTEGER
  • Phalcon\Db\Column::TYPE_DATE
  • Phalcon\Db\Column::TYPE_VARCHAR
  • Phalcon\Db\Column::TYPE_DECIMAL
  • Phalcon\Db\Column::TYPE_DATETIME
  • Phalcon\Db\Column::TYPE_CHAR
  • Phalcon\Db\Column::TYPE_TEXT

传入PhalconDb::createTable() 的相关数组可能含有的下标:

The associative array passed in Phalcon\Db::createTable() can have the possible keys:

IndexDescriptionOptional
“columns”An array with a set of table columns defined with Phalcon\Db\ColumnNo
“indexes”An array with a set of table indexes defined with Phalcon\Db\IndexYes
“references”An array with a set of table references (foreign keys) defined with Phalcon\Db\ReferenceYes
“options”An array with a set of table creation options. These options often relate to the database system in which the migration was generated.Yes

修改数据库表Altering Tables

随着你的应用的增长,作为一个重构的一部分,或者增加新功能,你也许需要修改你的数据库。 因为不是所有的数据库允许你修改已存在的字段或者添加字段在2个已存在的字段之间。所以 PhalconDb 会受到数据库系统的这些限制。

As your application grows, you might need to alter your database, as part of a refactoring or adding new features. Not all database systems allow to modify existing columns or add columns between two existing ones. Phalcon\Db is limited by these constraints.

  1. <?php
  2. use Phalcon\Db\Column as Column;
  3. // Adding a new column
  4. $connection->addColumn("robots", null,
  5. new Column("robot_type", array(
  6. "type" => Column::TYPE_VARCHAR,
  7. "size" => 32,
  8. "notNull" => true,
  9. "after" => "name"
  10. ))
  11. );
  12. // Modifying an existing column
  13. $connection->modifyColumn("robots", null, new Column("name", array(
  14. "type" => Column::TYPE_VARCHAR,
  15. "size" => 40,
  16. "notNull" => true,
  17. )));
  18. // Deleting the column "name"
  19. $connection->dropColumn("robots", null, "name");

删除数据库表Dropping Tables

删除数据库表的例子:

Examples on dropping tables:

  1. <?php
  2. // Drop table robot from active database
  3. $connection->dropTable("robots");
  4. //Drop table robot from database "machines"
  5. $connection->dropTable("robots", "machines");