CakePHP - 使用Paginator的虚拟领域问题?

时间:2014-10-29 17:09:07

标签: mysql cakephp paginator

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查询:SELECT OfficeidOfficecityDatafollowers FROM ebd。{ {1}} AS offices内部加入Officeebd AS data ON(DataOffice = id。{ {1}} AND年= 2014 AND月= 10 AND day = 01)WHERE 1 = 1 GROUP BY Dataoffice_id LIMIT 20

需要你的帮助谢谢

1 个答案:

答案 0 :(得分: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';

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