Phalcon:关于连接PHQL的特定列

时间:2015-09-03 04:04:36

标签: phalcon

以下PHQL生成一个复杂的结果集,如下所示:

$phql = "SELECT User.*, ProductUser.* "
      . "FROM ProductUser "
      . "INNER JOIN User "
      . "WHERE ProductUser.product_id = 5";

使用 ProductUser.id 等现有列替换 ProductUser。* 会导致错误:

  

MESSAGE:行中不存在索引
  文件:phalcon / mvc / model / row.zep
  LINE:67

这是2.0.6版。这是一个错误还是我在某处犯了错误?根据{{​​3}},它应该没问题。

2 个答案:

答案 0 :(得分:0)

这是我的错误(期望行始终是一个对象) 我希望这有助于某人,因为循环复杂的结果集不在文档中。

$result = $this->modelsManager->createQuery($phql)->execute();

if ($result instanceof \Phalcon\Mvc\Model\Resultset\Complex) {
    foreach ($result as $rows) {
        foreach ($rows as $row) {
            if (is_object($row)) {
                $modelData = $row->toArray());
            // this is what I needed
            } else {
                $id = $row;
            }
        }
    }
}

答案 1 :(得分:0)

首先,您错过了查询中的ON clause

无论如何,使用Phalcon's query builder进行查询会更容易且更容易出错:

<?php

// modelManager is avaiable in the default DI
$queryBuilder = $this->modelsManager->createBuilder();
$queryBuilder->from(["product" => 'Path\To\ProductUser']);

// Inner join params are: the model class path, the condition for the 'ON' clause, and optionally an alias for the table
$queryBuilder->innerJoin('Path\To\User', "product.user_id = user.id", "user");

$queryBuilder->columns([
    "product.*",
    "user.*"
]);

$queryBuilder->where("product.id = 5");

// You can use this line to debug what was generated
// $generatedQuery = $queryBuilder->getPhql();
// var_dump($generatedQuery);

// Finish the query building
$query = $queryBuilder->getQuery();

// Execute it and get the results
$result = $query->execute();

// Now use var_dump to see how the result was fetched
var_dump($result);
exit;