相关型号/表上的cakephp组

时间:2014-11-29 11:20:55

标签: cakephp cakephp-2.5

简短背景:我的订单包含名为'Komplexes'的产品。 Komplexes有不同的大小(高度和宽度),如果有多个Komplex具有相同的度量,它们必须被分组,并且必须添加一个计数器来为工人创建作业。

我的模特:

class Order extends AppModel {
public $hasMany = 'Komplex';
public $belongsTo = array(
    'Customer' => array(
        'counterCache' => true
    )
);
}


class Komplex extends AppModel {
public $belongsTo = array(
    'Order' => array(
        'counterCache' => true
    )
);
...<validation and calculations>
}

在我的OrdersController中,我从

开始
    public function orderproductionjob($id = NULL) {
    if (!$id) {
        throw new NotFoundException(__('Invalid ID'));
    }
    $order = $this->Order->find('all', array(
        'conditions' => array('Order.id =' => $id),
        'group' => array('Komplex.height')
    ));
    die(debug($order));

这给我一个数据库错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Komplex.height' in 'group statement'

没有'group'的'find'给了我正确的结果(解释了分组; - )

所以很明显我对这个小组做错了。我可以找到关于分析的例子和在网上和食谱中分组的例子,但这个组合没有被提及或者我可能没有找到它。因为这是我的第一个带有cakephp的项目,我希望,那个有更多经验的sombody可以帮助我。

我想在SQL中存档的内容:

SELECT orders.id, orders.name, komplexes.width, komplexes.height, count(komplexes.id) as Count
FROM orders, komplexes
WHERE orders.id = 1 AND komplexes.order_id = orders.id
group by komplexes.width, komplexes.height;

1 个答案:

答案 0 :(得分:1)

尝试在Komplex模型上将代码更改为Group。

$komplex = $this->Order->Komplex->find('all', array(
    'fields' => array('Komplex.height', 'Komplex.width', 'Count(*) as `Count`')
    'conditions' => array('Komplex.order_id =' => $id),
    'group' => array('Komplex.height', 'Komplex.width')
));

FYI

  1. 您的SQL语句有效,因为您保证只有1个订单行。如果您尝试加入超过1个订单行,它可能并且很可能会返回错误的结果。
  2. 您需要在语句中使用SQL保留字。在您的情况下Count作为别名列名称。你可能想要改变它。请注意,我的代码示例包含反引号包围的COUNT。