我可能错过了一些非常明显的东西。我试图在Cake中将多个表连接在一起,但我只从第一个表中获取字段。请考虑以下代码..
$joins = array();
$joins[] = array(
'table' => 'products',
'alias' => 'Product',
'type' => 'LEFT',
'conditions' => array(
'Device.id = Product.device_id'
)
);
$joins[] = array(
'table' => 'pricepoints',
'alias' => 'Pricepoints',
'type' => 'LEFT',
'conditions' => array(
'Pricepoints.product_id = Product.id'
)
);
$all_products = $this->Device->find('all', array("joins" => $joins);
这将返回以下SQL
SELECT `Device`.`id`, `Device`.`manufacturer_id`, `Device`.`name`, `Device`.`type_id`, `Manufacturer`.`id`, `Manufacturer`.`name` FROM `devices` AS `Device` LEFT JOIN products AS `Product` ON (`Device`.`id` = `Product`.`device_id`) LEFT JOIN pricepoints AS `Pricepoints` ON (`Pricepoints`.`product_id` = `Product`.`id`) LEFT JOIN `manufacturers` AS `Manufacturer` ON (`Device`.`manufacturer_id` = `Manufacturer`.`id`)
即。它只返回父模型中的字段ie。设备。如何从连接中选择所有字段?我认为它与我建立模型关系的方式有关,但我认为我已经正确设置了这些。
有人建议吗?
答案 0 :(得分:7)
您可以在查询查询中指定字段:
$all_products = $this->Device->find('all', array("fields" => array('Device.*','Product.*','Pricepoints.*')
"joins" => $joins
);
希望这有帮助
答案 1 :(得分:1)
通过调用bindModel()而不是手动指定连接来进行连接。有关creating and destroying associations on the fly
的详细信息,请参阅食谱