I have a use case as above. In my CategoriesController.php
, I do my query on Category
like below:
$category = $this->Category->Transaction->find("first", array(
"fields" => array("Category.*", "COUNT(*) AS TOTAL", "AVG(Transaction.debit) AS AVERAGE_COST"),
"conditions" => array("not" => array("Transaction.debit" => null)),
"contain" => array("Category" => array("CategoryType")),
"group" => "Transaction.category_id",
"order" => array("TOTAL" => "desc"),
));
and this is what I got in return:
Array
(
[Category] => Array
(
[id] => 2
[name] => FOOD
[category_type_id] => 2
)
[0] => Array
(
[TOTAL] => 4596
[AVERAGE_COST] => 7.668451
)
)
Question: How can I specify CategoryType
in the return fields?
I tried with Category.CategoryType.*
and CategoryType.*
and were not working. But if I take out the fields
array completely and let cakephp to handle by default, cakephp managed to return CategoryType in the array.
A couple of things to look for here:
Did you attach containable behavior to your category_type
model? from the book: When using ‘fields’ and ‘contain’ options - be careful to include all foreign keys that your query directly or indirectly requires. Please also note that because Containable must to be attached to all models used in containment, you may consider attaching it to your AppModel.
Since you are assigning the fields
outside of the containable parameters, this may be overriding your containable behavior. Consider moving "fields" => array("Category.*", "COUNT(*) AS TOTAL", "AVG(Transaction.debit) AS AVERAGE_COST"),
into your contains array.