sum() function in cakephp query - cakephp

I am using this query, but it is not returning ctotal. Please help.
$total = $this->RequestedItem->find('all',
[
'sum(cost * quantity) AS ctotal',
'conditions' => [
'RequestedItem.purchase_request_id' => $_GET['po_id']
]
]
);

You should not be using PHP superglobals directly in CakePHP. You should instead use Model.field naming so that you do not get ambiguous field errors.
Virtual fields is the way to go but that is not your problem, you need to read the book some more.
$total = $this->RequestedItem->find('all', array(array('fields' => array('sum(Model.cost * Model.quantity) AS ctotal'), 'conditions'=>array('RequestedItem.purchase_request_id'=>$this->params['named']['po_id'])));
should work fine, with the virtualFields it would be
var $virtualFields = array('total' => 'SUM(Model.cost * Model.quantity)');
$total = $this->RequestedItem->find('all', array(array('fields' => array('total'), 'conditions'=>array('RequestedItem.purchase_request_id'=>$this->params['named']['po_id'])));
Fields go in the 'fields' key, just like conditions go in the 'conditions' key. See http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find

This works too, worked fine for me
$sum = $this->Modelname->find('all', array(
'conditions' => array(
'Modelname.fieldname' => $conditions),
'fields' => array('sum(Modelname.fieldname) as total_sum'
)
)
);

Temporarily set the virtualFields prior to doing a find.
$this->MaterialScan->virtualFields = array(
'total_qty' => 'COUNT(MaterialScan.id)',
'total_lbs' => 'SUM(MaterialScan.weight)'
);
$materialScans = $this->MaterialScan->find('all',array(
'conditions' => array(
'MaterialScan.id' => $scans
),
'group' => array('MaterialScan.part_number')
));
This avoids having the [0] elements in the returned array.

You can use virtualFields:
var $virtualFields = array(
'the_sum' => 'SUM(Model.cost * Model.quantity)'
);

Related

cakephp find Model instead of read

I can't load my Model with 'find' but can load that with 'read'.
I want to get Model attributes by order. But I think 'read' function doesn't have that. How can I use 'find' instead of 'read'?
It works
$itemfiles = $this->Item->read(null, $id);
It doesn't work
$itemfiles = $this->Item->find('all', array(
'order' => array('Upload.order' => 'asc'),
'conditions' => array('Item.id' => $id)
));
And also is there any way to get data by order using 'read'?
You can do this like way
$itemfiles = $this->Item->Upload->find('all',
array (
'conditions' => array('Item.id' => $id),
'order' => array('Upload.order' => 'asc')
)
);

How to mix AND OR operators in find conditions CakePHP

I want to write this query in CakePHP:
SELECT * FROM pm_management.chk_master_xs_tasks
where (eq_model = 'D11 R' OR eq_model = 'TODOS') AND (pm_type = 'XD' OR pm_type = 'XS');
I have tried severals ways like this:
$this->ChkMasterXsTask->find('all', array(
'conditions' => array('AND' => array(
array('OR' => array('ChkMasterXsTask.eq_model' => $eq_model,
'ChkMasterXsTask.eq_model' => 'TODOS')),
array('OR' => array('ChkMasterXsTask.pm_type' => $pm_type,
'ChkMasterXsTask.pm_type' => 'XS'))
)
),
));
But the result is not the expected. Also I saw related questions but doesn't work for me.
Thank you so much for your answers.
Your problem arises from this code (and this problem is repeated for eq_model)
array('ChkMasterXsTask.pm_type' => $pm_type,
'ChkMasterXsTask.pm_type' => 'XS')
which tries to assign 2 values to the same key of that associative array. You could rewrite your code to this:
array(array('ChkMasterXsTask.pm_type' => $pm_type),
array('ChkMasterXsTask.pm_type' => 'XS'))
Another option which improves readability, uses SQL's IN function. The equivalent SQL becomes
SELECT *
FROM pm_management.chk_master_xs_tasks
WHERE eq_model IN ('D11 R', 'TODOS')
AND pm_type IN ('XD', 'XS');
Which should make your find a little easier write:
$this->ChkMasterXsTask->find('all', array(
'conditions' => array(
'ChkMasterXsTask.eq_model' => array($eq_model, 'TODOS'),
'ChkMasterXsTask.pm_type' => array($pm_type, 'XS'))
));
just I see a error y your code, there is a comma, that shouldn't be there.
$this->ChkMasterXsTask->find(
'all', array(
'conditions' => array(
'AND' =>
array('OR' => array(
array('ChkMasterXsTask.eq_model' => $eq_model),
array('ChkMasterXsTask.eq_model' => 'TODOS')
),
array('OR' =>
array('ChkMasterXsTask.pm_type' => $pm_type),
array('ChkMasterXsTask.pm_type' => 'XS')
)
))
));

CakePHP 2.x containable behavior conditions on deep associations

I have model relations like this:
Project hasMany SubProject hasMany Item
I want to set up a containable array so that I can find all of the Items which belong to a particular Project, and paginate the results. So, in my ItemsController I have:
public $paginate = array(
'Item' => array(
'limit' => 10,
'order' => array('
'Item.create_time' => 'desc'
),
'contain' => array(
'SubProject' => array(
'Project'
)
)
)
);
Somewhere, obviously, I need to place a condition like "SubProject.project_id = $pid", but nothing I've tried yields the correct results. The best I can manage is results that look like this:
Array
(
[0] => Array
(
[Item] => Array
(
[id] => 13
[file_name] => foo.tar.gz
.... other keys ...
[create_time] => 2013-01-23 14:59:49
[subProject_id] => 4
)
[SubProject] => Array
(
[id] => 4
[name] => foo
[project_id] => 2
..... other keys ....
[Project] => Array
(
)
)
)
[1] => Array
.....
Edit: It is quite correctly omitting the Project record that doesn't match; I want to skip any Item records with out a matching Project record.
It has crossed my mind to manually specify my joins, but I feel like that shouldn't be necessary.
It seems like this should be obvious, but alas, the solution escapes me.
I did eventually solve this problem, so I thought I'd explain what I did in the hope it might help someone else.
After reading this blog post by Mark Story (which is from the days of 1.2 but still relevant) I decided that the thing to do was create a custom find type in my Item model that binds the Project model directly. This gives a first-level association that Containable can filter correctly.
So, in the Items model, I have something like the following (see the documentation on custom find types).
public $findMethods = array('byProject' => true);
public function _findByProject($state, $query, $results=array()) {
if ($state == 'before') {
$this->bindModel(array(
'hasOne' => array(
'Project' => array(
'foreignKey' => false,
'conditions' => array('Project.id = SubProject.project_id')
)
)
));
return $query;
}
return $results;
}
Note that setting foreignKey to false is necessary to prevent CakePHP from trying to automatically use a non-existent database key. In the ItemsController, the pagination options now look like this:
public $paginate = array(
'Item' => array(
'findType' => 'byProject',
'limit' => 10,
'order' => array(
'Item.create_time' => 'desc'
),
'contain' => array(
'SubProject',
'Project'
),
'conditions' => array('Project.id' = $pid)
),
);
...where $pid is the id of the project to display. Some minor tweaks in the view code to accomodate the slightly different results array structure, and I was all set.
EDIT ===============
public $paginate = array(
'limit' => 10,
'order' => 'Item.create_time DESC', //'order' => array(''Item.create_time' => 'desc'),
'contain' => array(
'SubProject' => array(
'Project' => array(
'conditions' => array(
'id' => $project_id // Passed parameter
)
)
)
)
);
=================================================
Have you tried using conditions as in the following? Also, I did not write the 'order' section of the code the way you have it.
public $paginate = array(
'Item' => array(
'limit' => 10,
'order' => 'Item.create_time DESC', //'order' => array(''Item.create_time' => 'desc'),
'contain' => array(
'SubProject' => array(
'Project' => array(
'conditions' => array(
'id' => $project_id // Passed parameter
)
)
)
)
)
);

Add tables to custom query in cakephp

Im trying to replicate the following query in cakephp:
SELECT *
FROM uploads, proposals
WHERE proposals.id = uploads.proposal_id AND proposals.tender_id = 10
Im using the find method in the Upload model with the following conditions:
$conditions = array(
'Proposal.id' => $id,
'AND' => array(
'Upload.proposal_id' => 'Proposal.id'
)
);
return($this->find('list', array('conditions' => $conditions)));
but im getting this query instead
SELECT `Upload`.`id`, `Upload`.`title`
FROM `kumalabs_lic`.`uploads` AS `Upload`
WHERE `Proposal`.`id` = 10 AND `Upload`.`proposal_id` = 'Proposal.id'
as you can see, the proposals table is missing, can somebody explain me how can i make this query?
Thanks :)
I would recommend you use the linkable behaviour for this. It is much easier than the default way of doing joins in CakePHP. It works with the latest version of CakePHP, as well as 1.3.
CakePHP Linkable Behavior
You would then modify your find to look like this:
return($this->find('list', array(
'link' => array('Proposal'),
'conditions' => array(
'Proposal.id' => $id,
),
'fields' => array(
'Upload.*',
'Proposal.*',
),
)));
CakePHP will automatically join on your primary / foreign key, so no need to have the
'Upload.proposal_id' => 'Proposal.id'
condition.
Though you don't need that condition, I also want to point out that you are doing your AND wrong. This is how you do AND and OR in CakePHP
'conditions' => array(
'and' => array(
'field1' => 'value1', // Both of these conditions must be true
'field2' => 'value2'
),
'or' => array(
'field1' => 'value1', // One of these conditions must be true
'field2' => 'value2'
),
),
If the model have association, CakePHP automatically join the table by 'contain' keyword. Try code bellow:
public function getProposalsFromTender($id){
$data = $this->find('all', array(
'conditions' => array('Proposal.id' => $id),
'fields' => array('Upload.*', 'Proposal.*'),
'contain' => array('Proposal')
));
return($data);
}
Note:
CakePHP use explicit join instead of implicit join like ...from proposals, uploads...
I'm not familiar with that JOIN syntax but I believe it equals this:
SELECT *
FROM uploads
INNER JOIN proposals ON proposals.id = uploads.proposal_id
WHERE proposals.tender_id = 10
... so you need something similar to this:
// Untested
$conditions = array(
'Proposal.id' => $id,
'joins' => array(
array(
'alias' => 'Proposal',
'table' => 'proposals',
'type' => 'INNER',
'conditions' => 'Proposal.id = Upload.proposal_id',
),
),
);
Of course, this is a direct translation of your JOIN. If your models are properly related, it should all happen automatically.

cakephp find('list') for select box

I am trying to implement selectbox in my site.Option for that selectbox is set in my controller like below
$tmp_user = $this->User->find('first',array('id'=>$this->Auth->user('id')));
$zip_info = $this->Zipcode->find('first',array('id'=>#$tmp_user['User']['zip_id']));
$region_admins = $this->AdminRegion->find('all',array('conditions'=>array('AdminRegion.region_id'=>#$zip_info['Zipcode']['region_id'])));
if(!empty($region_admins)){
foreach($region_admins as $radmn):
//pr($radmn);
$admin_user = $this->User->find('list',array('conditions'=>array('id'=>$radmn['AdminRegion']['user_id']),'fields'=>array('id','username')));
pr($admin_user);
$this->set('users',$admin_user);
endforeach;
I am getting value like this when i print from controller
Array
(
[137] => governmentuser1
)
Array
(
[198] => testadmin
)
Array
(
[215] => adminregion
)
Array
(
[224] => testcompany1234
)
Array
(
[225] => testuser12345678
)
but only last value is set in select box....
Where did i made mistake?
How about something like this:
<?php
$tmp_user = $this->User->find('first', array(
'id' => $this->Auth->user('id')
));
$zip_info = $this->Zipcode->find('first', array(
'id' => #$tmp_user['User']['zip_id']
));
$region_admins = $this->AdminRegion->find('list', array(
'conditions' => array(
'AdminRegion.region_id' => #$zip_info['Zipcode']['region_id']
),
'fields' => array('AdminRegion.user_id', 'AdminRegion.user_id')
));
$admin_users = $this->User->find('list', array(
'conditions' => array(
'id' => $region_admins
),
'fields' => array(
'id','username'
)
));
?>
A few side notes:
Why do another query for the user data? Isn't it all in the session?
I wouldn't use the # anywhere, it's slower and suppresses errors. It will make debugging a nightmare too.
I think you missed array:
$admin_user[] = $this->User->find('list',array('conditions'=>array('id'=>$radmn['AdminRegion']['user_id']),'fields'=>array('id','username')));
Hope it helps

Resources