Phalcon 查询语言(Phalcon Query Language (PHQL))

Phalcon 查询语言(以下简称 PHQL)是一种面向对象的高级 SQL 方言,与标准化的 SQL 相似。Phalcon 内部实现了一个解析器(和 SQLite 中相似的解析器)语句解析成符合 RDBMS 的语法。

在 PHQL 中,我们实现一组特性使你对数据库的访问更安全:

  • 绑定参数,使你的代码更安全
  • 使用预处理语句
  • 忽略语句中的所有注释
  • 只允许数据操作语句,避免误修改、删除表或数据库
  • 允许在模型中处理表中字段
标识名不能添加引号(反单引号、单引号或双引号)。

范例(Usage Example)

通过下面的列子让我们更清除的了解 PHQL 是如何工作的。我们有两个模型 “Cars” 和 “Brands”:

  1. <?php
  2.  
  3. use Phalcon\Mvc\Model;
  4.  
  5. class Cars extends Model
  6. {
  7. public $id;
  8.  
  9. public $name;
  10.  
  11. public $brand_id;
  12.  
  13. public $price;
  14.  
  15. public $year;
  16.  
  17. public $style;
  18.  
  19. /**
  20. * This model is mapped to the table sample_cars
  21. */
  22. public function getSource()
  23. {
  24. return 'sample_cars';
  25. }
  26.  
  27. /**
  28. * A car only has a Brand, but a Brand have many Cars
  29. */
  30. public function initialize()
  31. {
  32. $this->belongsTo('brand_id', 'Brands', 'id');
  33. }
  34. }

每辆车都属于一个品牌,所以每个品牌下面拥有多辆车:

  1. <?php
  2.  
  3. use Phalcon\Mvc\Model;
  4.  
  5. class Brands extends Model
  6. {
  7. public $id;
  8.  
  9. public $name;
  10.  
  11. /**
  12. * The model Brands is mapped to the "sample_brands" table
  13. */
  14. public function getSource()
  15. {
  16. return 'sample_brands';
  17. }
  18.  
  19. /**
  20. * A Brand can have many Cars
  21. */
  22. public function initialize()
  23. {
  24. $this->hasMany('id', 'Cars', 'brand_id');
  25. }
  26. }

创建 PHQL 查询(Creating PHQL Queries)

PHQL 查询可以通过类 Phalcon\Mvc\Model\Query 进行实例化:

  1. <?php
  2.  
  3. use Phalcon\Mvc\Model\Query;
  4.  
  5. // Instantiate the Query
  6. $query = new Query("SELECT * FROM Cars", $this->getDI());
  7.  
  8. // Execute the query returning a result if any
  9. $cars = $query->execute();

在控制器或者视图中,利用注入服务 models manager 可以方便创建以及执行:

  1. <?php
  2.  
  3. // Executing a simple query
  4. $query = $this->modelsManager->createQuery("SELECT * FROM Cars");
  5. $cars = $query->execute();
  6.  
  7. // With bound parameters
  8. $query = $this->modelsManager->createQuery("SELECT * FROM Cars WHERE name = :name:");
  9. $cars = $query->execute(
  10. array(
  11. 'name' => 'Audi'
  12. )
  13. );

或者直接执行:

  1. <?php
  2.  
  3. // Executing a simple query
  4. $cars = $this->modelsManager->executeQuery("SELECT * FROM Cars");
  5.  
  6. // Executing with bound parameters
  7. $cars = $this->modelsManager->executeQuery("SELECT * FROM Cars WHERE name = :name:", array(
  8. 'name' => 'Audi'
  9. ));

选取记录(Selecting Records)

As the familiar SQL, PHQL allows querying of records using the SELECT statement we know, except that instead of specifying tables, we use the models classes:

  1. <?php
  2.  
  3. $query = $manager->createQuery("SELECT * FROM Cars ORDER BY Cars.name");
  4. $query = $manager->createQuery("SELECT Cars.name FROM Cars ORDER BY Cars.name");

Classes in namespaces are also allowed:

  1. <?php
  2.  
  3. $phql = "SELECT * FROM Formula\Cars ORDER BY Formula\Cars.name";
  4. $query = $manager->createQuery($phql);
  5.  
  6. $phql = "SELECT Formula\Cars.name FROM Formula\Cars ORDER BY Formula\Cars.name";
  7. $query = $manager->createQuery($phql);
  8.  
  9. $phql = "SELECT c.name FROM Formula\Cars c ORDER BY c.name";
  10. $query = $manager->createQuery($phql);

Most of the SQL standard is supported by PHQL, even nonstandard directives such as LIMIT:

  1. <?php
  2.  
  3. $phql = "SELECT c.name FROM Cars AS c "
  4. . "WHERE c.brand_id = 21 ORDER BY c.name LIMIT 100";
  5. $query = $manager->createQuery($phql);

结果类型(Result Types)

Depending on the type of columns we query, the result type will vary. If you retrieve a single whole object, then the object returned isa Phalcon\Mvc\Model\Resultset\Simple. This kind of resultset is a set of complete model objects:

  1. <?php
  2.  
  3. $phql = "SELECT c.* FROM Cars AS c ORDER BY c.name";
  4. $cars = $manager->executeQuery($phql);
  5. foreach ($cars as $car) {
  6. echo "Name: ", $car->name, "\n";
  7. }

This is exactly the same as:

  1. <?php
  2.  
  3. $cars = Cars::find(
  4. array(
  5. "order" => "name"
  6. )
  7. );
  8.  
  9. foreach ($cars as $car) {
  10. echo "Name: ", $car->name, "\n";
  11. }

Complete objects can be modified and re-saved in the database because they represent a complete record of the associated table. There areother types of queries that do not return complete objects, for example:

  1. <?php
  2.  
  3. $phql = "SELECT c.id, c.name FROM Cars AS c ORDER BY c.name";
  4. $cars = $manager->executeQuery($phql);
  5. foreach ($cars as $car) {
  6. echo "Name: ", $car->name, "\n";
  7. }

We are only requesting some fields in the table, therefore those cannot be considered an entire object, so the returned object isstill a resultset of type Phalcon\Mvc\Model\Resultset\Simple. However, each element is a standardobject that only contain the two columns that were requested.

These values that don’t represent complete objects are what we call scalars. PHQL allows you to query all types of scalars: fields, functions, literals, expressions, etc..:

  1. <?php
  2.  
  3. $phql = "SELECT CONCAT(c.id, ' ', c.name) AS id_name FROM Cars AS c ORDER BY c.name";
  4. $cars = $manager->executeQuery($phql);
  5. foreach ($cars as $car) {
  6. echo $car->id_name, "\n";
  7. }

As we can query complete objects or scalars, we can also query both at once:

  1. <?php
  2.  
  3. $phql = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c ORDER BY c.name";
  4. $result = $manager->executeQuery($phql);

The result in this case is an object Phalcon\Mvc\Model\Resultset\Complex.This allows access to both complete objects and scalars at once:

  1. <?php
  2.  
  3. foreach ($result as $row) {
  4. echo "Name: ", $row->cars->name, "\n";
  5. echo "Price: ", $row->cars->price, "\n";
  6. echo "Taxes: ", $row->taxes, "\n";
  7. }

Scalars are mapped as properties of each “row”, while complete objects are mapped as properties with the name of its related model.

连接(Joins)

It’s easy to request records from multiple models using PHQL. Most kinds of Joins are supported. As we definedrelationships in the models, PHQL adds these conditions automatically:

  1. <?php
  2.  
  3. $phql = "SELECT Cars.name AS car_name, Brands.name AS brand_name FROM Cars JOIN Brands";
  4. $rows = $manager->executeQuery($phql);
  5. foreach ($rows as $row) {
  6. echo $row->car_name, "\n";
  7. echo $row->brand_name, "\n";
  8. }

By default, an INNER JOIN is assumed. You can specify the type of JOIN in the query:

  1. <?php
  2.  
  3. $phql = "SELECT Cars.*, Brands.* FROM Cars INNER JOIN Brands";
  4. $rows = $manager->executeQuery($phql);
  5.  
  6. $phql = "SELECT Cars.*, Brands.* FROM Cars LEFT JOIN Brands";
  7. $rows = $manager->executeQuery($phql);
  8.  
  9. $phql = "SELECT Cars.*, Brands.* FROM Cars LEFT OUTER JOIN Brands";
  10. $rows = $manager->executeQuery($phql);
  11.  
  12. $phql = "SELECT Cars.*, Brands.* FROM Cars CROSS JOIN Brands";
  13. $rows = $manager->executeQuery($phql);

It is also possible to manually set the conditions of the JOIN:

  1. <?php
  2.  
  3. $phql = "SELECT Cars.*, Brands.* FROM Cars INNER JOIN Brands ON Brands.id = Cars.brands_id";
  4. $rows = $manager->executeQuery($phql);

Also, the joins can be created using multiple tables in the FROM clause:

  1. <?php
  2.  
  3. $phql = "SELECT Cars.*, Brands.* FROM Cars, Brands WHERE Brands.id = Cars.brands_id";
  4. $rows = $manager->executeQuery($phql);
  5. foreach ($rows as $row) {
  6. echo "Car: ", $row->cars->name, "\n";
  7. echo "Brand: ", $row->brands->name, "\n";
  8. }

If an alias is used to rename the models in the query, those will be used to name the attributes in the every row of the result:

  1. <?php
  2.  
  3. $phql = "SELECT c.*, b.* FROM Cars c, Brands b WHERE b.id = c.brands_id";
  4. $rows = $manager->executeQuery($phql);
  5. foreach ($rows as $row) {
  6. echo "Car: ", $row->c->name, "\n";
  7. echo "Brand: ", $row->b->name, "\n";
  8. }

When the joined model has a many-to-many relation to the ‘from’ model, the intermediate model is implicitly added to the generated query:

  1. <?php
  2.  
  3. $phql = 'SELECT Artists.name, Songs.name FROM Artists ' .
  4. 'JOIN Songs WHERE Artists.genre = "Trip-Hop"';
  5. $result = $this->modelsManager->executeQuery($phql);

This code executes the following SQL in MySQL:

  1. SELECT `artists`.`name`, `songs`.`name` FROM `artists`
  2. INNER JOIN `albums` ON `albums`.`artists_id` = `artists`.`id`
  3. INNER JOIN `songs` ON `albums`.`songs_id` = `songs`.`id`
  4. WHERE `artists`.`genre` = 'Trip-Hop'

聚合(Aggregations)

The following examples show how to use aggregations in PHQL:

  1. <?php
  2.  
  3. // How much are the prices of all the cars?
  4. $phql = "SELECT SUM(price) AS summatory FROM Cars";
  5. $row = $manager->executeQuery($phql)->getFirst();
  6. echo $row['summatory'];
  7.  
  8. // How many cars are by each brand?
  9. $phql = "SELECT Cars.brand_id, COUNT(*) FROM Cars GROUP BY Cars.brand_id";
  10. $rows = $manager->executeQuery($phql);
  11. foreach ($rows as $row) {
  12. echo $row->brand_id, ' ', $row["1"], "\n";
  13. }
  14.  
  15. // How many cars are by each brand?
  16. $phql = "SELECT Brands.name, COUNT(*) FROM Cars JOIN Brands GROUP BY 1";
  17. $rows = $manager->executeQuery($phql);
  18. foreach ($rows as $row) {
  19. echo $row->name, ' ', $row["1"], "\n";
  20. }
  21.  
  22. $phql = "SELECT MAX(price) AS maximum, MIN(price) AS minimum FROM Cars";
  23. $rows = $manager->executeQuery($phql);
  24. foreach ($rows as $row) {
  25. echo $row["maximum"], ' ', $row["minimum"], "\n";
  26. }
  27.  
  28. // Count distinct used brands
  29. $phql = "SELECT COUNT(DISTINCT brand_id) AS brandId FROM Cars";
  30. $rows = $manager->executeQuery($phql);
  31. foreach ($rows as $row) {
  32. echo $row->brandId, "\n";
  33. }

条件(Conditions)

Conditions allow us to filter the set of records we want to query. The WHERE clause allows to do that:

  1. <?php
  2.  
  3. // Simple conditions
  4. $phql = "SELECT * FROM Cars WHERE Cars.name = 'Lamborghini Espada'";
  5. $cars = $manager->executeQuery($phql);
  6.  
  7. $phql = "SELECT * FROM Cars WHERE Cars.price > 10000";
  8. $cars = $manager->executeQuery($phql);
  9.  
  10. $phql = "SELECT * FROM Cars WHERE TRIM(Cars.name) = 'Audi R8'";
  11. $cars = $manager->executeQuery($phql);
  12.  
  13. $phql = "SELECT * FROM Cars WHERE Cars.name LIKE 'Ferrari%'";
  14. $cars = $manager->executeQuery($phql);
  15.  
  16. $phql = "SELECT * FROM Cars WHERE Cars.name NOT LIKE 'Ferrari%'";
  17. $cars = $manager->executeQuery($phql);
  18.  
  19. $phql = "SELECT * FROM Cars WHERE Cars.price IS NULL";
  20. $cars = $manager->executeQuery($phql);
  21.  
  22. $phql = "SELECT * FROM Cars WHERE Cars.id IN (120, 121, 122)";
  23. $cars = $manager->executeQuery($phql);
  24.  
  25. $phql = "SELECT * FROM Cars WHERE Cars.id NOT IN (430, 431)";
  26. $cars = $manager->executeQuery($phql);
  27.  
  28. $phql = "SELECT * FROM Cars WHERE Cars.id BETWEEN 1 AND 100";
  29. $cars = $manager->executeQuery($phql);

Also, as part of PHQL, prepared parameters automatically escape the input data, introducing more security:

  1. <?php
  2.  
  3. $phql = "SELECT * FROM Cars WHERE Cars.name = :name:";
  4. $cars = $manager->executeQuery($phql, array("name" => 'Lamborghini Espada'));
  5.  
  6. $phql = "SELECT * FROM Cars WHERE Cars.name = ?0";
  7. $cars = $manager->executeQuery($phql, array(0 => 'Lamborghini Espada'));

插入数据(Inserting Data)

With PHQL it’s possible to insert data using the familiar INSERT statement:

  1. <?php
  2.  
  3. // Inserting without columns
  4. $phql = "INSERT INTO Cars VALUES (NULL, 'Lamborghini Espada', "
  5. . "7, 10000.00, 1969, 'Grand Tourer')";
  6. $manager->executeQuery($phql);
  7.  
  8. // Specifying columns to insert
  9. $phql = "INSERT INTO Cars (name, brand_id, year, style) "
  10. . "VALUES ('Lamborghini Espada', 7, 1969, 'Grand Tourer')";
  11. $manager->executeQuery($phql);
  12.  
  13. // Inserting using placeholders
  14. $phql = "INSERT INTO Cars (name, brand_id, year, style) "
  15. . "VALUES (:name:, :brand_id:, :year:, :style)";
  16. $manager->executeQuery(
  17. $phql,
  18. array(
  19. 'name' => 'Lamborghini Espada',
  20. 'brand_id' => 7,
  21. 'year' => 1969,
  22. 'style' => 'Grand Tourer',
  23. )
  24. );

Phalcon doesn’t only transform the PHQL statements into SQL. All events and business rules definedin the model are executed as if we created individual objects manually. Let’s add a business ruleon the model cars. A car cannot cost less than $ 10,000:

  1. <?php
  2.  
  3. use Phalcon\Mvc\Model;
  4. use Phalcon\Mvc\Model\Message;
  5.  
  6. class Cars extends Model
  7. {
  8. public function beforeCreate()
  9. {
  10. if ($this->price < 10000) {
  11. $this->appendMessage(new Message("A car cannot cost less than $ 10,000"));
  12. return false;
  13. }
  14. }
  15. }

If we made the following INSERT in the models Cars, the operation will not be successfulbecause the price does not meet the business rule that we implemented. By checking thestatus of the insertion we can print any validation messages generated internally:

  1. <?php
  2.  
  3. $phql = "INSERT INTO Cars VALUES (NULL, 'Nissan Versa', 7, 9999.00, 2015, 'Sedan')";
  4. $result = $manager->executeQuery($phql);
  5. if ($result->success() == false) {
  6. foreach ($result->getMessages() as $message) {
  7. echo $message->getMessage();
  8. }
  9. }

更新数据(Updating Data)

Updating rows is very similar than inserting rows. As you may know, the instruction toupdate records is UPDATE. When a record is updated the events related to the update operationwill be executed for each row.

  1. <?php
  2.  
  3. // Updating a single column
  4. $phql = "UPDATE Cars SET price = 15000.00 WHERE id = 101";
  5. $manager->executeQuery($phql);
  6.  
  7. // Updating multiples columns
  8. $phql = "UPDATE Cars SET price = 15000.00, type = 'Sedan' WHERE id = 101";
  9. $manager->executeQuery($phql);
  10.  
  11. // Updating multiples rows
  12. $phql = "UPDATE Cars SET price = 7000.00, type = 'Sedan' WHERE brands_id > 5";
  13. $manager->executeQuery($phql);
  14.  
  15. // Using placeholders
  16. $phql = "UPDATE Cars SET price = ?0, type = ?1 WHERE brands_id > ?2";
  17. $manager->executeQuery(
  18. $phql,
  19. array(
  20. 0 => 7000.00,
  21. 1 => 'Sedan',
  22. 2 => 5
  23. )
  24. );

An UPDATE statement performs the update in two phases:

  • First, if the UPDATE has a WHERE clause it retrieves all the objects that match these criteria,
  • Second, based on the queried objects it updates/changes the requested attributes storing them to the relational database
    This way of operation allows that events, virtual foreign keys and validations take part of the updating process.In summary, the following code:
  1. <?php
  2.  
  3. $phql = "UPDATE Cars SET price = 15000.00 WHERE id > 101";
  4. $result = $manager->executeQuery($phql);
  5. if ($result->success() == false) {
  6. foreach ($result->getMessages() as $message) {
  7. echo $message->getMessage();
  8. }
  9. }

is somewhat equivalent to:

  1. <?php
  2.  
  3. $messages = null;
  4.  
  5. $process = function () use (&$messages) {
  6. foreach (Cars::find("id > 101") as $car) {
  7. $car->price = 15000;
  8. if ($car->save() == false) {
  9. $messages = $car->getMessages();
  10. return false;
  11. }
  12. }
  13. return true;
  14. };
  15.  
  16. $success = $process();

删除数据(Deleting Data)

When a record is deleted the events related to the delete operation will be executed for each row:

  1. <?php
  2.  
  3. // Deleting a single row
  4. $phql = "DELETE FROM Cars WHERE id = 101";
  5. $manager->executeQuery($phql);
  6.  
  7. // Deleting multiple rows
  8. $phql = "DELETE FROM Cars WHERE id > 100";
  9. $manager->executeQuery($phql);
  10.  
  11. // Using placeholders
  12. $phql = "DELETE FROM Cars WHERE id BETWEEN :initial: AND :final:";
  13. $manager->executeQuery(
  14. $phql,
  15. array(
  16. 'initial' => 1,
  17. 'final' => 100
  18. )
  19. );

DELETE operations are also executed in two phases like UPDATEs. To check if the deletion producesany validation messages you should check the status code returned:

  1. // Deleting multiple rows
  2. $phql = "DELETE FROM Cars WHERE id > 100";
  3. $result = $manager->executeQuery($phql);
  4. if ($result->success() == false) {
  5. foreach ($result->getMessages() as $message) {
  6. echo $message->getMessage();
  7. }
  8. }

使用查询构建器创建查询(Creating queries using the Query Builder)

A builder is available to create PHQL queries without the need to write PHQL statements, also providing IDE facilities:

选取查询构建器(Select Query Builder)

  1. <?php
  2.  
  3. // Create a new Query Builder for Select
  4. $robots = $this->modelsManager->createBuilder();
  5. // Or
  6. $builder = Phalcon\Mvc\Model\Query\Builder::create(Phalcon\Mvc\Model\Query::TYPE_SELECT);
  7. // Or
  8. $builder = Phalcon\Mvc\Model\Query\Builder::createSelectBuilder();
  9.  
  10. // Getting a whole set
  11. $builder->from('Robots')
  12. ->join('RobotsParts')
  13. ->orderBy('Robots.name')
  14. ->getQuery()
  15. ->execute();
  16.  
  17. // Getting the first row
  18. $builder->from('Robots')
  19. ->join('RobotsParts')
  20. ->orderBy('Robots.name')
  21. ->getQuery()
  22. ->getSingleResult();

That is the same as:

  1. <?php
  2.  
  3. $phql = "SELECT Robots.* FROM Robots JOIN RobotsParts p ORDER BY Robots.name LIMIT 20";
  4. $result = $manager->executeQuery($phql);

More examples of the builder:

  1. <?php
  2.  
  3. // 'SELECT Robots.* FROM Robots';
  4. $builder->from('Robots');
  5.  
  6. // 'SELECT Robots.*, RobotsParts.* FROM Robots, RobotsParts';
  7. $builder->from(
  8. array(
  9. 'Robots',
  10. 'RobotsParts'
  11. )
  12. );
  13.  
  14. // 'SELECT * FROM Robots';
  15. $phql = $builder->columns('*')
  16. ->from('Robots');
  17.  
  18. // 'SELECT id FROM Robots';
  19. $builder->columns('id')
  20. ->from('Robots');
  21.  
  22. // 'SELECT id, name FROM Robots';
  23. $builder->columns(array('id', 'name'))
  24. ->from('Robots');
  25.  
  26. // 'SELECT Robots.* FROM Robots WHERE Robots.name = "Voltron"';
  27. $builder->from('Robots')
  28. ->where('Robots.name = "Voltron"');
  29.  
  30. // 'SELECT Robots.* FROM Robots WHERE Robots.id = 100';
  31. $builder->from('Robots')
  32. ->where(100);
  33.  
  34. // 'SELECT Robots.* FROM Robots WHERE Robots.type = "virtual" AND Robots.id > 50';
  35. $builder->from('Robots')
  36. ->where('type = "virtual"')
  37. ->andWhere('id > 50');
  38.  
  39. // 'SELECT Robots.* FROM Robots WHERE Robots.type = "virtual" OR Robots.id > 50';
  40. $builder->from('Robots')
  41. ->where('type = "virtual"')
  42. ->orWhere('id > 50');
  43.  
  44. // 'SELECT Robots.* FROM Robots GROUP BY Robots.name';
  45. $builder->from('Robots')
  46. ->groupBy('Robots.name');
  47.  
  48. // 'SELECT Robots.* FROM Robots GROUP BY Robots.name, Robots.id';
  49. $builder->from('Robots')
  50. ->groupBy(array('Robots.name', 'Robots.id'));
  51.  
  52. // 'SELECT Robots.name, SUM(Robots.price) FROM Robots GROUP BY Robots.name';
  53. $builder->columns(array('Robots.name', 'SUM(Robots.price)'))
  54. ->from('Robots')
  55. ->groupBy('Robots.name');
  56.  
  57. // 'SELECT Robots.name, SUM(Robots.price) FROM Robots GROUP BY Robots.name HAVING SUM(Robots.price) > 1000';
  58. $builder->columns(array('Robots.name', 'SUM(Robots.price)'))
  59. ->from('Robots')
  60. ->groupBy('Robots.name')
  61. ->having('SUM(Robots.price) > 1000');
  62.  
  63. // 'SELECT Robots.* FROM Robots JOIN RobotsParts';
  64. $builder->from('Robots')
  65. ->join('RobotsParts');
  66.  
  67. // 'SELECT Robots.* FROM Robots JOIN RobotsParts AS p';
  68. $builder->from('Robots')
  69. ->join('RobotsParts', null, 'p');
  70.  
  71. // 'SELECT Robots.* FROM Robots JOIN RobotsParts ON Robots.id = RobotsParts.robots_id AS p';
  72. $builder->from('Robots')
  73. ->join('RobotsParts', 'Robots.id = RobotsParts.robots_id', 'p');
  74.  
  75. // 'SELECT Robots.* FROM Robots
  76. // JOIN RobotsParts ON Robots.id = RobotsParts.robots_id AS p
  77. // JOIN Parts ON Parts.id = RobotsParts.parts_id AS t';
  78. $builder->from('Robots')
  79. ->join('RobotsParts', 'Robots.id = RobotsParts.robots_id', 'p')
  80. ->join('Parts', 'Parts.id = RobotsParts.parts_id', 't');
  81.  
  82. // 'SELECT r.* FROM Robots AS r';
  83. $builder->addFrom('Robots', 'r');
  84.  
  85. // 'SELECT Robots.*, p.* FROM Robots, Parts AS p';
  86. $builder->from('Robots')
  87. ->addFrom('Parts', 'p');
  88.  
  89. // 'SELECT r.*, p.* FROM Robots AS r, Parts AS p';
  90. $builder->from(array('r' => 'Robots'))
  91. ->addFrom('Parts', 'p');
  92.  
  93. // 'SELECT r.*, p.* FROM Robots AS r, Parts AS p';
  94. $builder->from(array('r' => 'Robots', 'p' => 'Parts'));
  95.  
  96. // 'SELECT Robots.* FROM Robots LIMIT 10';
  97. $builder->from('Robots')
  98. ->limit(10);
  99.  
  100. // 'SELECT Robots.* FROM Robots LIMIT 10 OFFSET 5';
  101. $builder->from('Robots')
  102. ->limit(10, 5);
  103.  
  104. // 'SELECT Robots.* FROM Robots WHERE id BETWEEN 1 AND 100';
  105. $builder->from('Robots')
  106. ->betweenWhere('id', 1, 100);
  107.  
  108. // 'SELECT Robots.* FROM Robots WHERE id IN (1, 2, 3)';
  109. $builder->from('Robots')
  110. ->inWhere('id', array(1, 2, 3));
  111.  
  112. // 'SELECT Robots.* FROM Robots WHERE id NOT IN (1, 2, 3)';
  113. $builder->from('Robots')
  114. ->notInWhere('id', array(1, 2, 3));
  115.  
  116. // 'SELECT Robots.* FROM Robots WHERE name LIKE '%Art%';
  117. $builder->from('Robots')
  118. ->where('name LIKE :name:', array('name' => '%' . $name . '%'));
  119.  
  120. // 'SELECT r.* FROM Store\Robots WHERE r.name LIKE '%Art%';
  121. $builder->from(['r' => 'Store\Robots'])
  122. ->where('r.name LIKE :name:', array('name' => '%' . $name . '%'));

插入查询构建器(Insert Query Builder)

  1. <?php
  2.  
  3. // Create a new Query Builder for Insert
  4. $robots = $this->modelsManager->createBuilder(NULL, Phalcon\Mvc\Model\Query::TYPE_INSERT);
  5. // Or
  6. $builder = Phalcon\Mvc\Model\Query\Builder::create(Phalcon\Mvc\Model\Query::TYPE_INSERT);
  7. // Or
  8. $builder = Phalcon\Mvc\Model\Query\Builder::createInsertBuilder();
  9.  
  10. // Insert two records
  11. $builder->table('Robots')
  12. ->columns(array('name'))
  13. ->values(array(array('name' => 'Google'), array('name' => 'Baidu')))
  14. ->getQuery()
  15. ->execute();

更新查询构建器(Update Query Builder)

  1. <?php
  2.  
  3. // Create a new Query Builder for Update
  4. $robots = $this->modelsManager->createBuilder(NULL, Phalcon\Mvc\Model\Query::TYPE_UPDATE);
  5. // Or
  6. $builder = Phalcon\Mvc\Model\Query\Builder::create(Phalcon\Mvc\Model\Query::TYPE_UPDATE);
  7. // Or
  8. $builder = Phalcon\Mvc\Model\Query\Builder::createUpdateBuilder();
  9.  
  10. // Update records
  11. $builder->table('Robots')
  12. ->set(array('name' => 'Google'))
  13. ->getQuery()
  14. ->execute();

删除查询构建器(Delete Query Builder)

  1. <?php
  2.  
  3. // Create a new Query Builder for Delete
  4. $robots = $this->modelsManager->createBuilder(NULL, Phalcon\Mvc\Model\Query::TYPE_DELETE);
  5. // Or
  6. $builder = Phalcon\Mvc\Model\Query\Builder::create(Phalcon\Mvc\Model\Query::TYPE_DELETE);
  7. // Or
  8. $builder = Phalcon\Mvc\Model\Query\Builder::createDeleteBuilder();
  9.  
  10. // Delete records
  11. $builder->table('Robots')
  12. ->where('name = "Peter"')
  13. ->orderBy('Robots.id')
  14. ->limit(20)
  15. ->getQuery()
  16. ->execute();

绑定参数(Bound Parameters)

Bound parameters in the query builder can be set as the query is constructed or past all at once when executing:

  1. <?php
  2.  
  3. // Passing parameters in the query construction
  4. $robots = $this->modelsManager->createBuilder()
  5. ->from('Robots')
  6. ->where('name = :name:', array('name' => $name))
  7. ->andWhere('type = :type:', array('type' => $type))
  8. ->getQuery()
  9. ->execute();
  10.  
  11. // Passing parameters in query execution
  12. $robots = $this->modelsManager->createBuilder()
  13. ->from('Robots')
  14. ->where('name = :name:')
  15. ->andWhere('type = :type:')
  16. ->getQuery()
  17. ->execute(array('name' => $name, 'type' => $type));

禁止使用字面值(Disallow literals in PHQL)

Literals can be disabled in PHQL, this means that directly using strings, numbers and boolean values in PHQL stringswill be disallowed. If PHQL statements are created embedding external data on them, this could open the applicationto potential SQL injections:

  1. <?php
  2.  
  3. $login = 'voltron';
  4. $phql = "SELECT * FROM Models\Users WHERE login = '$login'";
  5. $result = $manager->executeQuery($phql);

If $login is changed to ' OR '' = ', the produced PHQL is:

  1. SELECT * FROM Models\Users WHERE login = '' OR '' = ''

Which is always true no matter what the login stored in the database is.

If literals are disallowed strings can be used as part of a PHQL statement, thus an exceptionwill be thrown forcing the developer to use bound parameters. The same query can be written in asecure way like this:

  1. <?php
  2.  
  3. $phql = "SELECT Robots.* FROM Robots WHERE Robots.name = :name:";
  4. $result = $manager->executeQuery($phql, array('name' => $name));

You can disallow literals in the following way:

  1. <?php
  2.  
  3. use Phalcon\Mvc\Model;
  4.  
  5. Model::setup(
  6. array(
  7. 'phqlLiterals' => false
  8. )
  9. );

Bound parameters can be used even if literals are allowed or not. Disallowing them is justanother security decision a developer could take in web applications.

转义保留字(Escaping Reserved Words)

PHQL has a few reserved words, if you want to use any of them as attributes or models names, you need to escape thosewords using the cross-database escaping delimiters ‘[‘ and ‘]’:

  1. <?php
  2.  
  3. $phql = "SELECT * FROM [Update]";
  4. $result = $manager->executeQuery($phql);
  5.  
  6. $phql = "SELECT id, [Like] FROM Posts";
  7. $result = $manager->executeQuery($phql);

The delimiters are dynamically translated to valid delimiters depending on the database system where the application is currently running on.

PHQL 生命周期(PHQL Lifecycle)

Being a high-level language, PHQL gives developers the ability to personalize and customize different aspects in order to suit their needs.The following is the life cycle of each PHQL statement executed:

  • The PHQL is parsed and converted into an Intermediate Representation (IR) which is independent of the SQL implemented by database system
  • The IR is converted to valid SQL according to the database system associated to the model
  • PHQL statements are parsed once and cached in memory. Further executions of the same statement result in a slightly faster execution

使用原生 SQL(Using Raw SQL)

A database system could offer specific SQL extensions that aren’t supported by PHQL, in this case, a raw SQL can be appropriate:

  1. <?php
  2.  
  3. use Phalcon\Mvc\Model;
  4. use Phalcon\Mvc\Model\Resultset\Simple as Resultset;
  5.  
  6. class Robots extends Model
  7. {
  8. public static function findByCreateInterval()
  9. {
  10. // A raw SQL statement
  11. $sql = "SELECT * FROM robots WHERE id > 0";
  12.  
  13. // Base model
  14. $robot = new Robots();
  15.  
  16. // Execute the query
  17. return new Resultset(null, $robot, $robot->getReadConnection()->query($sql));
  18. }
  19. }

If Raw SQL queries are common in your application a generic method could be added to your model:

  1. <?php
  2.  
  3. use Phalcon\Mvc\Model;
  4. use Phalcon\Mvc\Model\Resultset\Simple as Resultset;
  5.  
  6. class Robots extends Model
  7. {
  8. public static function findByRawSql($conditions, $params = null)
  9. {
  10. // A raw SQL statement
  11. $sql = "SELECT * FROM robots WHERE $conditions";
  12.  
  13. // Base model
  14. $robot = new Robots();
  15.  
  16. // Execute the query
  17. return new Resultset(null, $robot, $robot->getReadConnection()->query($sql, $params));
  18. }
  19. }

The above findByRawSql could be used as follows:

  1. <?php
  2.  
  3. $robots = Robots::findByRawSql('id > ?', array(10));

实现读写分离(Reading and Writing Separation)

当查询器中实现此方法,将会替换 模型 中实现的方法,实现读写分离代码如下:

  1. <?php
  2.  
  3. class MyQuery extends Phalcon\Mvc\Model\Query
  4. {
  5. /**
  6. * 动态选择读数据库连接
  7. *
  8. * @param array $data
  9. */
  10. public function selectReadConnection($data)
  11. {
  12. $intermediate = $data[0];
  13. $bindParams = $data[1];
  14. $bindTypes = $data[2];
  15. return $this->getDI()->get('readDB');
  16. }
  17.  
  18. /**
  19. * 动态选择写数据库连接
  20. *
  21. * @param array $intermediate
  22. * @param array $bindParams
  23. * @param array $bindTypes
  24. */
  25. public function selectWriteConnection($data)
  26. {
  27. $intermediate = $data[0];
  28. $bindParams = $data[1];
  29. $bindTypes = $data[2];
  30. return $this->getDI()->get('writeDB');
  31. }
  32. }
  33.  
  34. $di->set('modelsQuery', 'MyQuery');

分库(Split Database)

根据当前查询条件来实现,实现水平切分的功能:

  1. <?php
  2.  
  3. $di->modelsQuery->attachEvent('selectReadConnection', function($event, $data) {
  4. $intermediate = $data[0];
  5. $bindParams = $data[1];
  6. $bindTypes = $data[2];
  7.  
  8. // Check if there is a 'where' clause in the select
  9. if (isset($intermediate['where'])) {
  10.  
  11. $conditions = $intermediate['where'];
  12.  
  13. // Choose the possible shard according to the conditions
  14. if ($conditions['left']['name'] == 'id') {
  15. $id = $conditions['right']['value'];
  16.  
  17. if ($id > 0 && $id < 10000) {
  18. return $this->getDI()->get('dbShard1');
  19. }
  20.  
  21. if ($id > 10000) {
  22. return $this->getDI()->get('dbShard2');
  23. }
  24. }
  25. }
  26.  
  27. // Use a default shard
  28. return $this->getDI()->get('dbShard0');
  29. });
  30.  
  31. // Or
  32. class MyQuery extends Phalcon\Mvc\Model\Query
  33. {
  34. /**
  35. * 动态选择读数据库连接
  36. *
  37. * @param array $intermediate
  38. * @param array $bindParams
  39. * @param array $bindTypes
  40. */
  41. public function selectReadConnection($event, $data)
  42. {
  43. $intermediate = $data[0];
  44. $bindParams = $data[1];
  45. $bindTypes = $data[2];
  46.  
  47. // Check if there is a 'where' clause in the select
  48. if (isset($intermediate['where'])) {
  49.  
  50. $conditions = $intermediate['where'];
  51.  
  52. // Choose the possible shard according to the conditions
  53. if ($conditions['left']['name'] == 'id') {
  54. $id = $conditions['right']['value'];
  55.  
  56. if ($id > 0 && $id < 10000) {
  57. return $this->getDI()->get('dbShard1');
  58. }
  59.  
  60. if ($id > 10000) {
  61. return $this->getDI()->get('dbShard2');
  62. }
  63. }
  64. }
  65.  
  66. // Use a default shard
  67. return $this->getDI()->get('dbShard0');
  68. }
  69. }
  70.  
  71. $di->set('modelsQuery', 'MyQuery');

PHQL 事件(PHQL Events)

如果需要的话 Phalcon\MvcModelQuery 可以发送事件到 EventsManager 。支持如下的事件:

事件名 触发条件 能否中止操作 能否返回值
beforePrepareSelect No No
afterPrepareSelect No No
beforePrepareInsert No No
afterPrepareInsert No No
beforePrepareUpdate No No
afterPrepareUpdate No No
beforePrepareDelete No No
afterPrepareDelete No No
beforeParse No No
afterParse No No
beforeExecute No No
afterExecute No No
beforeGenerateSQLStatement No No
afterGenerateSQLStatement No Yes
beforeExecuteSelect No No
afterExecuteSelect No No
beforeExecuteInsert No No
afterExecuteInsert No No
beforeExecuteUpdate No No
afterExecuteUpdate No No
beforeExecuteDelete No No
afterExecuteDelete No No

PHQL 事件(PHQL Events)

注意事项(Troubleshooting)

在使用 PHQL 我们需要注意一些事项:

  • 类名是区分大小写的,如果 PHQL 使用的类名和真实的类名不一致,这在一些操作系统中可能会导致意外行为,比如 Linux 之类的区分大小写的文件系统。
  • 必须在定义数据库连接时,设置正确的字符集参数。
  • 在 PHQL 中,类的别名不能取代带完整命名空间的类,因为这只是字符串。
  • 如果启用了列重命名,则避免使用与重命名的列同名的列别名,这可能会混淆查询解析器。

原文: http://www.myleftstudio.com/reference/phql.html