CakePHP发现没有在查询中插入正确的引号

时间:2014-08-30 19:10:37

标签: php mysql cakephp find

我正在使用此代码制作按类型计算和排序的卡车类型列表。

$count['type'] = $this->Type->find('all',
        array('joins' => array(
            array(
                'table' => 'truck_has_types',
                'alias' => 'TruckHasTypes',
                'type' => 'LEFT',
                'conditions' => array(
                    'Type.id' => 'TruckHasTypes.types_id',
                )
            )
        ),
        'fields' => array(
            'Type.id',
            'Type.name',
            'COUNT(TruckHasTypes.types_id) as N'),
            'group' => 'TruckHasTypes.types_id'
        )
    );

查询只返回一个结果,即使应该还有更多。我找到了罪魁祸首。查询看起来像这样(从sql_dump获得)

SELECT `Type`.`id`, `Type`.`name`, COUNT(`TruckHasTypes`.`types_id`) as N FROM `douglass_cake`.`types` AS `Type` LEFT JOIN `douglass_cake`.`truck_has_types` AS `TruckHasTypes` ON (`Type`.`id` = 'TruckHasTypes.types_id') WHERE 1 = 1 GROUP BY `TruckHasTypes`.`types_id`

你可以看到

ON (`Type`.`id` = 'TruckHasTypes.types_id')

没有与

相同的引号
ON (`Type`.`id` = `TruckHasTypes`.`types_id`)

我在phpmyadmin中手动添加了这些引号并且查询成功,但我不能让cakephp自动生成此查询。有什么想法吗?

谢谢! 莱恩

2 个答案:

答案 0 :(得分:1)

这样做:

$count['type'] = $this->Type->find('all',
    array(
        'joins' => array(
            array(
                'table' => 'truck_has_types',
                'alias' => 'TruckHasTypes',
                'type' => 'LEFT',
                'conditions' => array(
                    'Type.id=TruckHasTypes.types_id',
                )
            )
        ),
        'fields' => array(
            'Type.id',
            'Type.name',
            'COUNT(TruckHasTypes.types_id) as N'
        ),
        'group' => 'TruckHasTypes.types_id'
    )
);

答案 1 :(得分:0)

而不是写joins做它"蛋糕方式" - 写模型关联:Associations: Linking Models Together

'group' => 'TruckHasTypes.types_id'还需要一级吗?