I am trying to do the following nested select statement with CakePHP buildStatement function but to no avail.
select * from
(
select i.id, i.name Item, sum(t.qty) Total, l.name Location
from transactions t
left join locations l on (l.id = t.location_id)
left join items i on (i.id = t.item_id)
where t.item_id = 855
group by location_id )
filter where total <> 0
I hope some expert can help with this!
My try ashamed:
$subqueryOptions = array(
'fields' => array('Item.id', 'Item.name', 'SUM(Transaction.qty) total', 'Location.name'),
'conditions' => array(
'Transaction.item_id'=>855,
),
'joins'=>array(
'Location',
'Item'
),
'group'=>array(
'Transaction.location_id'
),
'table'=>'transactions Transaction'
);
$db = $this->Transaction->getDataSource();
$subQuery = $db->buildStatement($subqueryOptions, $this->Transaction);
$res = $this->Transaction->find('all', array(
'fields'=>$subQuery,
'conditions' => array('total !='=>0)
));`
resulting statement:
SELECT `SELECT Item.id`, `Item`.`name`, SUM(`Transaction`.`qty`) total, `Location.name
FROM transactions Transaction AS Location Item
WHERE `Transaction`.`item_id` = 855
GROUP BY `Transaction`.`location_id``
FROM `biruni-inventory`.`transactions` AS `Transaction`
LEFT JOIN `biruni-inventory`.`transaction_types` AS `TransactionType`
ON (`Transaction`.`transaction_type_id` = `TransactionType`.`id`)
LEFT JOIN `biruni-inventory`.`item_conditions` AS `ItemCondition`
ON (`Transaction`.`item_condition_id` = `ItemCondition`.`id`)
LEFT JOIN `biruni-inventory`.`locations` AS `Location`
ON (`Transaction`.`location_id`= `Location`.`id`)
WHERE `total` != 0
which is totally irrelevant!