0

phpMyAdmin 中的以下 SQL 查询完全符合我的预期:

SELECT d.office_id, o.city, sum(d.`nb_followers`) as total_followers  FROM `data` as d
LEFT JOIN offices as o on d.office_id = o.id

WHERE d.`year` = 2014 AND d.`month` = 10 AND d.`day` = 01
Group by d.`office_id`
ORDER BY total_followers DESC limit 10

在我的控制器中:

 $this->Paginator->virtualFields = array(
            'followers' => 'SUM(Data.nb_followers)',
            'id' => 'Office.office_id'
        );


        $this->Paginator->settings = array(
            'fields' => array('id', 'Office.city', 'Data.followers'),
            'joins' => array(
                array(
                    'table' => 'data',
                    'alias' => 'Data',
                    'type' => 'inner',
                    'conditions' => array(
                        'Office.id = Data.office_id',
                        'year = ' . date('Y', mktime(0, 0, 0, date('m'), 1, date('Y'))),
                        'month = ' . date('m', mktime(0, 0, 0, date('m'), 1, date('Y'))),
                        'day = 01'
                    )
                )
            ),
            'group' => array('Data.id'), //Mal positionné à la base mais vérifier si activé n'impacte pas les résultats
            'order' => array('Data.followers' => 'desc')
            //'limit' => 1
        );
        $dataTop = $this->paginate('Office');

但我得到这个错误:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Data.followers' in 'field list'

SQL 查询:选择Officeid, Office. city, Data. followersebdoffices作为Office内部 JOIN ebddataAS DataON ( Office. id= Data. office_idAND year = 2014 AND month = 10 AND day = 01) WHERE 1 = 1 GROUP BY Dataid限制 20

需要你的帮助 谢谢

4

1 回答 1

0

我在我的网络应用程序中进行了测试,并在我的一个模型中放置了一个虚拟字段。虚拟字段是相关表中的字段,它似乎不起作用。它输出一个sql错误。所以我从文档中记住了子查询命令。

http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#sub-queries

我不知道这是否有效,但我会尝试给你一个可能适合你需要的例子

$db = $this->Office->getDataSource();

$subQuery = $db->buildStatement(
    array(
        'fields'     => array('followers' => 'SUM(Data.nb_followers)'),
        'table'      => 'datas',
        'alias'      => 'Data'
    ),
    $this->office);

$fields[] = $subQuery;
$fields[] = 'id';
$fields[] = 'Office.city';

我希望这能引导你走向正确的方向。

于 2014-10-29T18:10:11.293 回答