如何在PhalconPHP中运行RAW SQL查询

时间:2014-01-05 13:25:23

标签: php mysql crosstab phalcon

我尝试从此查询中获取结果

$sql = "
                SET @col = NULL;
                SET @sql = NULL;

                Select
                  Group_Concat(Distinct
                    Concat(
                      'SUM(CASE WHEN tbl.sdate = ''',
                      colname,
                      ''' THEN tbl.result ELSE NULL END) AS ''',
                      colname,''''
                    )
                  ) Into @col
                From (
                    select concat(month(i.invdate),'.',year(i.invdate)) as colname
                    from invoices as i
                    where i.invtype = 1 and i.pid = 5
                    order by i.invdate  
                ) As collst;

                SET @sql = CONCAT('SELECT tbl.wrkname,', @col, ' 
                                        FROM (
                                            Select wl.wgname As wrkname, Concat(Month(i.invdate),''.'',Year(i.invdate)) as sdate, Sum(id.qty * id.price) As result
                                            From invoices As i
                                                Join invoicedetails As id
                                                    On i.pchid = id.pchid
                                                Join workgroups As w
                                                    On i.wid = w.wid
                                                Join workgrouplist As wl
                                                    On w.wglid = wl.wglid
                                            Where i.invtype = ', 1, ' And i.pid =', 5,
                                            ' Group By i.pid, sdate
                                            Order By i.invdate, wrkname
                                        ) AS tbl
                                        GROUP BY tbl.wrkname');

                PREPARE stmt FROM @sql;
                EXECUTE stmt;
                DEALLOCATE PREPARE stmt;
                "

但结果是“SQLSTATE [HY000]:一般错误”。

Phalcon版本:1.2.4

Profiler日志是:

SQL Statement: SET @col = NULL; SET @sql = NULL; Select Group_Concat(Distinct Concat( 'SUM(CASE WHEN tbl.sdate = ''', colname, ''' THEN tbl.result ELSE NULL END) AS ''', colname,'''' ) ) Into @col From ( select concat(month(i.invdate),'.',year(i.invdate)) as colname from invoices as i where i.invtype = 1 and i.pid = 5 order by i.invdate   ) As collst; SET @sql = CONCAT('SELECT tbl.wrkname,', @col, ' FROM ( Select wl.wgname As wrkname, Concat(Month(i.invdate),''.'',Year(i.invdate)) as sdate, Sum(id.qty * id.price) As result From invoices As i Join invoicedetails As id On i.pchid = id.pchid Join workgroups As w On i.wid = w.wid Join workgrouplist As wl On w.wglid = wl.wglid Where i.invtype = ', 1, ' And i.pid =', 5, ' Group By i.pid, sdate Order By i.invdate, wrkname ) AS tbl GROUP BY tbl.wrkname'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; 
Start Time: 1388927869.2788
Final Time: 1388927869.2808
Total Elapsed Time: 0.0019619464874268

问题解决了:我创建了存储过程并插入了所有查询。 接下来我在php脚本中调用存储过程。

$sql = "CALL GetReportByProjectBetweenDates(1, 5)";
$result = $this->db->query($sql); 

6 个答案:

答案 0 :(得分:10)

我只看到你的SQL,你想展示你是如何在phalcon中运行它的吗?

在不使用模型或元数据的情况下运行原始SQL的一种简单方法是使用基本适配器,在本例中我将使用PDO:

        $connection = new Phalcon\Db\Adapter\Pdo\Mysql(array(
              'host' => 'localhost',
              'username' => 'user',
              'password' => 'password',
              'dbname' => 'optional'
        ));

        $connection->connect();

        $sql = 'select * from database.table';

        $result_set = $connection->query($sql);
        $result_set->setFetchMode(Phalcon\Db::FETCH_ASSOC);
        $result_set = $result_set->fetchAll($result_set);

答案 1 :(得分:7)

在控制器上运行原始sql:

$this->db->query("SELECT * FROM robots WHERE id > 0");

在模型上运行原始sql:

$this->getDi()->getShared('db')->query("SELECT * FROM robots WHERE id > 0");

答案 2 :(得分:6)

来自documentation

  

如果Raw SQL查询在您的应用程序中很常见,则为通用方法   可以添加到您的模型中:

<?php

use Phalcon\Mvc\Model\Resultset\Simple as Resultset;

class Robots extends Phalcon\Mvc\Model
{
    public static function findByRawSql($conditions, $params=null)
    {
        // A raw SQL statement
        $sql = "SELECT * FROM robots WHERE $conditions";

        // Base model
        $robot = new Robots();

        // Execute the query
        return new Resultset(null, $robot, $robot->getReadConnection()->query($sql, $params));
    }
}  

答案 3 :(得分:2)

根据david.duncan的答案,工作版:P(缺少逗号添加+数组打印)

$con = new Phalcon\Db\Adapter\Pdo\Mysql(array(
        'host' => 'localhost',
        'username' => '',
        'password' => '',
        'dbname' => 'aDatabase'
    ));

    $con->connect();
    $sql = 'select * from aDatabase.aTable';
    $result = $con->query($sql);
    $result->setFetchMode(Phalcon\Db::FETCH_ASSOC);
    $result = $result->fetchAll($result);

    foreach($result as $one)
    {
        echo print_r($one) . '<br>';
    }

答案 4 :(得分:0)

$sql = 'SELECT * from table'; 
$query = $this->modelsManager->createQuery( $sql);
$logs  = $query->execute(); 

对于modelsManager,您需要在服务中设置(service.php)

$di->set('modelsManager', function() {
      return new Phalcon\Mvc\Model\Manager\ModelsManager();
});

答案 5 :(得分:0)

您可以使用$ this-> db-> query(...)-> fetchAll(); 例如:

 $resultMaster = $this->db->query("SELECT users.personelcode, users.fullname, users.shift," .
        " users.unit,users.vahed,users.status,devices.id,devices.installedcity," .
        " archive.userid,archive.verifydate,archive.verifytime,archive.verifytype,archive.verifystate,archive.fromdevice," .
        " requests.fromuser,requests.kind,requests.status,requests.fromdate,requests.todate FROM personels as users" .
        " INNER JOIN devices ON users.unit = devices.installedcity INNER JOIN archive ON devices.id = archive.fromdevice" .
        " INNER JOIN requests ON requests.fromuser = users.personelcode WHERE archive.verifydate" .
        " BETWEEN '" . addslashes($startDate) . "' AND '" . addslashes($endDate) . "' AND users.unit = '" . addslashes($Office) . "' AND " .
        " archive.userid = users.idindvc AND users.vahed = '" . addslashes($Vahed) . "' ")->fetchAll();