Phalcon:加入PHQL的特定列

Phalcon: specific column on joined PHQL

下面的 PHQL 生成了一个复杂的结果集:

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

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

MESSAGE: The index does not exist in the row
FILE: phalcon/mvc/model/row.zep
LINE: 67

这是版本 2.0.6。这是一个错误还是我在某处犯了错误?按照documentation应该没问题

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

$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;
            }
        }
    }
}

首先,您在查询中遗漏了 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;