cakephp sum() on single field - cakephp

I have searched high and low on how to just get a total of a field called points. I just need one total figure but the best I can get is a list of records from the Points table with the associated records from the Members.
$totalPoints = $this->Member->Point->find('all', array(
array('fields' => array('sum(Point.points) AS Point.ctotal'))));

Why not using virtualFields as documented and suggested by the docs?
http://book.cakephp.org/2.0/en/models/virtual-fields.html
$this->Member->Point->virtualFields['total'] = 'SUM(Point.points)';
$totalPoints = $this->Member->Point->find('all', array('fields' => array('total')));
This is way cleaner.
Also note the double array you got there in your $options array (...find('all', array(array(...). And how I used only a single/flat array.
This is the reason why your SUM() call as fields does not work.

mark's answer above is right. I just want to add that you can do this:
$totalPoints = $this->Member->Point->find('first', array(
array('fields' => array('sum(Point.points) AS Point__ctotal'))));
$totalPoints will be have this:
$totalPoints['Point']['ctotal']

Another clean way without outputting an array
$this->Member->Point->virtualFields = array('total' => 'SUM(Point.points)');
$total = $this->Member->Point->field('total');

Related

How to retrieve data from model using findByType in cakephp?

I am trying to find records from CallForwardingCondition model using following line of code:
$this->loadModel('CallForwardingCondition');
$this->set('callForwardingCondition', $this->CallForwardingCondition->findByType('list'));
In SQL Dump following query is done when page is reloaded:
SELECT `CallForwardingCondition`.`type`, `CallForwardingCondition`.`description` FROM `vpbx`.`call_forwarding_condition` AS `CallForwardingCondition` WHERE `CallForwardingCondition`.`type` = 'list' LIMIT 1
How can I direct Cakephp to findByType which will result in following query?
SELECT `CallForwardingCondition`.`type`, `CallForwardingCondition`.`description` FROM `vpbx`.`call_forwarding_condition` AS `CallForwardingCondition` WHERE `CallForwardingCondition`.`type` LIKE '%' LIMIT 10
For CakePHP 2.x you need to use find('all') and pass it the required conditions and limit:-
$result = $this->CallForwardingCondition->find('all',[
'conditions' => ['CallForwardingCondition.type Like' => '%'],
'limit' => 10
);
findByType is a special find method that will only return the first record matching the type passed as the find method's parameter which is why it isn't returning what you want. You can read more about the findBy magic functions in the official docs.
try this:
$result = $this-> CallForwardingCondition ->find('all',['limit'=>10,'conditions'=>['CallForwardingCondition.type Like'=>'%'])->toArray();
I don't think you can't use findBy with limit. If you want to use limit, you must use findAllBy<fieldName>. Even findAllBy<fieldName>, you can't use LIKE.
This is findAllBy from cakephp
findAllBy<fieldName>(string $value, array $fields, array $order, int $limit, int $page, int $recursive)
So if you want to covert it, you must do the following way;
$this->CallForwardingCondition->findAllByType('something',['CallForwardingCondition.*'],['CallForwardingCondition.id'=>'desc'],'10');
This is findBy from cakephp doc.
findBy<fieldName>(string $value[, mixed $fields[, mixed $order]]);
Hope this help for you.

Dynamically add virtual field in cakephp

I am using CakePHP 2.1.3; I want to create a virtual field dynamically in a controller. Is it possible?
The problem is when I am trying to find max value in a table it gives me another array from the model array. Please ask if you need more information.
When I am trying to execute the following query,
$find_max_case_count = $this->CaseMaster->find('first', array(
'conditions' => array(
'CaseMaster.CLIENT_ID' => $client_id,
'CaseMaster.CASE_NO LIKE' => '%-%'
),
'fields' => array('max(CaseMaster.CASE_NO) AS MAX_NO')
));
It is giving me an array like:
[0]=> array([MAX_NO]=> 52)
However I want it to be like as:
[CaseMaster] => array([MAX_NO] => 52)
I found a solution. I can make the virtual field at runtime. The code should looks like:
$this->CaseMaster->virtualFields['MAX_NO'] = 0;
Write it just above the find query and the query will remain same as it was written.
This link was helpful to find out the solution.
There is no way (as far as I am knowledgeable) to create virtual fields "on the fly". What virtual fields are is "arbitrary SQL expressions" that will be executed when a find runs through the Model and "will be indexed under the Model's key alongside other Model fields".
What do you need to do with "dynamically created virtual fields"? If you explain what exactly you need to accomplish maybe we can provide a different (even more suitable? :) ) solution? I'd personally be happy to help you.
After you editing your question I can say that what you're getting is the way the array should be returned, this is because of the fields parameter. If you want to get a different structure out of it I suggest applying a callback to format it.
Firstly move the method inside the CaseMaster Model:
public function getMaxCaseCount($client_id){
$data = $this->find('first', array(
'conditions' => array(
'CaseMaster.CLIENT_ID' => $client_id,
'CaseMaster.CASE_NO LIKE' => '%-%'),
'fields' => array('max(CaseMaster.CASE_NO) AS MAX_NO')));
return array_map(array('CaseMaster', '__filterMaxCaseCount'), $data);
}
private function __filterMaxCaseCount($input){
//This is just an example formatting
//You can do whatever you would like here.
$output['CaseMaster'] = $input[0];
return $output;
}
The array_map function will apply the __filterMaxCaseCount callback method so that when you call:
$this->CaseMaster->getMaxCaseCount($client_id);
from your controller you will get the data in the way you need it. The array_map function could also look like this:
return array_map(array($this, '__filterMaxCaseCount'), $data);
because you're in the same Class.
Just adding your model alias to field definition also works for this purpose
'fields' => array('max(CaseMaster.CASE_NO) AS CaseMaster__MAX_NO')

CakePHP GROUP and COUNT items returned in list

I know there are some similar quesiton like this on here but they are all about when using
Model->find('all');
But thats not what I am doing, I am doing:
Model->find('list');
Which is whats making the difference between this working and not working.
Given a group of Products I want to find all the brands in that group and how many of each brand.
Sounds simple enough, here is what I did:
$fields = array('Product.brand','COUNT(`Product`.`brand`) AS brand_count')
$brand_data = $this->Product->find('list',array(
'fields'=>$fields,
'conditions'=>$conditions,
'recursive'=>0,
'group' => 'Product.brand'
));
debug($brand_data);
In this I am telling it to give me an array where the Keys are Product.brand and the values are COUNT(Product.brand)
I am getting this:
Array
(
[Brand A] =>
[Brand B] =>
[Brand C] =>
)
When I am expected this:
Array
(
[Brand A] => 534
[Brand B] => 243
[Brand C] => 172
)
It works if I do all instead of list though, it just gives me a much more complicated array to drill through. I am fine using all, I just first wanted to see if there was a reason why its not working in list?
Brief recap: find('list') has problems with aliased fields (and therefore aggregate functions like COUNT() etc.), so you should use CakePHP's 1.3 instead. For CakePHP 1.2 uses there's a contraption.
Detailed:
Most likely problem lies in your
COUNT(`Product.brand`) AS brand_count
Because find('list') does
Set::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath'])
on results of query, where $lst['valuePath'] would be
"{n}.COUNT(`Product`.`brand`) AS brand_count"
while in results it would be actually "{n}.Product.brand_count" - doesn't line up.
Try making your COUNT() a virtual field.
I.e.:
//model
var $virtualFields = array(
'brand_count' => 'COUNT(Product.brand)'
);
//controller
$fields = array('Product.brand','Product.brand_count');
In controller in Paginator you can use like this:
$itemads = $this->paginate($itemads, ['contain' => ['Departments', 'Stores'],'group'=>'upc','fields'=>array("upc_count"=>"COUNT(`upc`)")]);

Cake HABTM Query, Order By Rand()

I'm aware that Cake HABTM associations are tricky at the best of times, but I seem to be making life even harder for myself...
If I want to return a random Item from the db, I can do it as follows in the Item model:
$random = $this->find('first', array(
'order' => 'rand()'
));
and if I want to find all the Items that are in a certain Category (where Item has a HABTM relationship to Categories), I know I can get a result set through $this->Categories->find.
My question is: how can I combine the two, so I can return a random Item that belongs to a specified Category? Is there any easy way? (If not, I'll gladly take any suggestions for a laborious way, as long as it works ;)
ETA: I can get some of the way with Containable, maybe: say I add the line
'contain' => array('Categories'=>array('conditions'=>array('Categories.id'=>1))),
then the Item results that I don't want come back with an empty Categories array, to distinguish them from "good" items. But really I don't want said Item results to be returned at all...
ETA(2): I can get a workaround going by unsetting my results in the afterFind if the Categories array is empty (thanks to http://nuts-and-bolts-of-cakephp.com/2008/08/06/filtering-results-returned-by-containable-behavior/ for the tip), and then having my random find function not give up until it gets a result:
while (!is_array($item)) {
$item = $this->random($cat);
}
but ugh, could this be any clunkier? Anyway, time for me to stop editing my question, and to go away and sleep on it instead!
Try this:
<?php
$this->Item->bindModel(array('hasOne' => array('ItemsCategory')));
$random = $this->Item->find('all', array(
'order' => 'rand()',
'conditions' => array('ItemsCategory.category_id' => '1')
));
?>

Select from a table where associated table fieldname = 'x' in Cake PHP

In CakePHP, I have two tables, Countries & Networks. They have a HABTM relationship and are joined by countries_networks.
I'm trying to get all countries from the countries table where the 'name' field in Networks = 'o2'
I've realised I can't do this using a basic find(), so I've been experimenting with the containable behaviour. I have managed to restrict the returned data, but it looks as though 'containable' doesn't exactly work as I want. Heres my code:
$countries = $this->Country->find('all', array('contain' => array(
'Network' => array(
'conditions' => array('Network.name =' => "o2"),
)
)));
This query however returns ALL countries, and the Network.name if its 'o2'. What I really need to do is return ONLY the countries that have a Network.name of 'o2', and no others.
Can anyone help? Thanks.
"=' =>"
What is it? there is no needed to use "=" symbol after "Network.name"
Your query returns you exactly what your ask.
Try to select from Network.
$countries = $this->Country->Network->find('first', array(
'conditions' => array('Network.name' => "o2"),
'contain' => array('Country')
));
$countries = $countries['Country'];
You should be able to do something like this:
$this->Country->hasAndBelongsToMany['Network']['conditions'] = array('Network.name'=>'o2');
$myCountries = $this->Country->find('all');
I haven't tested this, but it should get you pretty close to where you need to be.
Also, bear in mind that changing the hasAndBelongsToMany array like this will affect all subsequent queries against that model during the current page load (but it will be reset the next time the model is instantiated).
I'm on my way out the door, so sorry for the brief explanation.
I think what you want is a HABTM relationship, but to be able to filter based on the associated model's data. To do this, check out the "Containable" behavior in Cake's manual. Pretty sure that's what you're after.

Resources