how to get sum of column in datatable using cakephp - cakephp

I have database column (wallet) in table (users).
how can I get total amount of (wallet) where role_id = 2 ?
what can I use find('list') and SUM?
I'm using cakephp 2
I got error, can you help me to fix it?
var $virtualFields = array('total_m' => 'SUM(User.wallet)');
$total_m = $this->RequestedItem->find('all', array(array('fields' => array('total_m'), 'conditions'=>array('RequestedItem.role_id'= 2 )));

$query = $this->Users->find();
$query->select(['role_id', 'sum' => $query->func()->sum('wallet')])
->where(['role_id' => 2]);
retun $query;
Start learning:
https://book.cakephp.org/3.0/en/orm/query-builder.html#using-sql-functions

Related

Counting and categorising instances of certain fields

I'm currently writing a survey style app that has some models:
Assessments
Recommendations
An assessment has many recommendations and is joined by the assessments_recommendations table, and I store data in the join table which are effectively answers.
One such answer is user impact. This field is an integer value between 0 and 10 and is different for each assessment->recommendation.
What I want to be able to do is send a count and categorisation of that field into a view so that I can chart it using chart.js. For example, I would like:
0-3 = Low
4-7 = Moderate
8-10 = High
As far as I can tell, I need to pass something along the lines of:
$counts [4, 6, 8]
$legend ['Low', 'Moderate', 'High']
So in the above example, 4 assessment->recommendations are classed as low, 6 are moderate, 8 are high.
Does anyone have any advice on how to do this in my controller? I've been reading up on collections but I'm not sure that is the correct way of doing this. I had issues as my data is stored in the _joinData part of the array and I couldn't figure out how to access it.
Any advice would be much appreciated.
Thanks!
Edit 1
This is the controller code I have been playing around with to get an initial collection working. The col variable passes through nicely and I can see this in the view. I get 'unknown getter' error on the join data line though. It isn't entirely clear to me from the docs what variables are what in the example in the book, so I've been very much trying every combo I can think of to try and get it to work before even trying to move on with the complete scenario.
public function view($id = null)
{
$this->loadModel ('Assessments');
$this->loadModel ('Recommendations');
$query = $this->Assessments->find('all', [
'conditions' => ['Assessments.id =' => $id],
'contain' => ['Recommendations']
]);
$assessment = $query->first();
$collection = new Collection($assessment->ToArray());
$countHigh = $collection->countBy(function ($assessment) {
return $assessment->_joinData->_user_impact > 7 ? 'High' : 'Error';
});
$this->set('assessments', $assessment);
$this->set('col', $collection);
$this->set('user_impact_high', $countHigh);
}
Edit 2
So I'm testing this some more. Trying to simplify it. Even using the groupBy function in it's simple form is failing. The code below generates the following error.
public function view($id = null)
{
$this->loadModel ('Assessments');
$this->loadModel ('Recommendations');
$query = $this->Assessments->find('all', [
'conditions' => ['Assessments.id =' => $id],
'contain' => ['Recommendations']
]);
$assessment = $query->first();
$collection = new Collection($assessment->ToArray());
$test = $collection->groupBy('client_id');
$this->set('assessments', $assessment);
$this->set('col', $collection);
$this->set('test', $test);
}
Error:
Cannot use object of type Cake\I18n\FrozenTime as array

Cakephp2. save data is adding two more rows

public function index($tin=null) {
$this->layout = 'index_1';
$this->loadModel('Insurance');
$this->loadModel('Verification');
$this->loadModel('Insurance_price');
$date = date('Y-m-d');
$verification_fee=$this->Insurance_price->findByInsurance_type("Third Party Auto Insurance");
$ver = $verification_fee['Insurance_price']['verification_amount'];
if(!empty($tin)) {
$this->request->data['tin'] = $tin;
$this->request->data['amount'] = $ver;
$this->request->data['date'] = date('Y-m-d');
$this->Verification->save($this->request->data);
$this->Verification->clear($this->request->data);
}
}
That's my controller. I am trying to save those data once the page loads.
But when I check the database table instead of seeing only 1 new record I see 3 new rows with the same data as 'amount' and 'date', except for tin column which will have 'image'.
What could I be doing wrong?
try inserting
$this->Verification->create();
before
$this->Verification->save($this->request->data);
And check

Cakephp 3 : How to get max amout row from a table

I have table call users , like
id name amount created
1 a 100 6-16-2016
2 b 200 5-16-2016
I need max amount full row, I have tried below code but getting syntax error.
$user = $this->Users->find('all',[
'fields' => array('MAX(Users.amount) AS amount'),
]);
simplest way
$user = $this->Users->find('all',[
'fields' => array('amount' => 'MAX(Users.id)'),
]);
using select instead of an options array
$user = $this->Users->find()
->select(['amount' => 'MAX(Users.id)']);
making use of cake SQL functions
$query = $this->Users->find();
$user = $query
->select(['amount' => $query->func()->max('Users.id')]);
the above three all give the same results
if you want to have a single record you have to call ->first() on the query object:
$user = $user->first();
$amount = $user->amount;
Simplest method using CakePHP 3:
$this->Model->find('all')->select('amount')->hydrate(false)->max('amount')
Will result in an array containing the maximum amount in that table column.
Is is better to disable hydration before getting the results, to get the results as an array, instead of entity. Below is a complete example of how to get the results in an array, with distinct steps:
//create query
$query = $this->Users->find('all',[
'fields' => array('amount' => 'MAX(Users.id)'),
]);
$query->enableHydration(false); // Results as arrays instead of entities
$results = $query->all(); // Get ResultSet that contains array data.
$maxAmount = $results->toList(); // Once we have a result set we can get all the rows

How to put where conditions with group by in cakephp find all query

I have created sql query which is working fine.
But i want to convert this sql query in cakephp format.
I try to convert this query in cakephp but
i am not understanding how to apply where conditions with group by clause.
And i only need to select this column u_data.lane_id AS LaneId, origin_city.pcode AS origin_pcode, dest_city.pcode AS dest_pcode....
not all columns from table.
plz help me to do this.
$options['conditions'] = array(
'CustomerRoute.portfolio_id' => '".$_SESSION["portfolioid"]."'
);
$content = $this->Customer->find('all', $options);
You simply need to define "group" and "fields" within $options-
Instead of $_SESSION, you should stick to the convention and use $this->Session->read instead.
//Eg: $_SESSION["portfolioid"] can be replaced with $this->Session->read("portfolioid")
$options['conditions'] = array(
"CustomerRoute.portfolio_id" => $this->Session->read("portfolioid"),
"u_data.supplier_id" => $this->Session->read("supplierid")
);
$options['fields'] = array(
"u_data.lane_id AS LaneId",
"origin_city.pcode AS origin_pcode",
"dest_city.pcode AS dest_pcode"
); // Add this
$options['group'] = array('CustomerRoute.id'); // Add this
$content = $this->Customer->find('all', $options);
This should give you what you're looking for.
Peace! xD

CakePHP 2.x : How to get last insert single field in controller?

I have a tansaction table and have a field called balance. Here I am trying to update this field with new data but insert in new transaction. So I need balance field in controller. So, I have tried below code.
$client_id = $this->request->data['Transaction']['user_id'];
$new = $this->Transaction->find('first', array(
'conditions'=>array('Transaction.user_id'=> $client_id),
'fields'=>array('Transaction.balance')
));
$this->request->data['Transaction']['balance'] =$this->request->data['Transaction']['debit_money']-$this->request->data['Transaction']['credit_money']+new;
But here I am not getting old balance data.
$new is an associative array. You are adding an array to a number.
Try the following:
$client_id = $this->request->data['Transaction']['user_id'];
$new = $this->Transaction->find('first', array(
'conditions'=>array('Transaction.user_id'=> $client_id),
'fields'=>array('Transaction.balance')
));
$this->request->data['Transaction']['balance'] =
$this->request->data['Transaction']['debit_money']
- $this->request->data['Transaction']['credit_money']
+ $new['Transaction']['balance'];
Alternatively, this should also work:
$client_id = $this->request->data['Transaction']['user_id'];
$this->request->data['Transaction']['balance'] =
$this->request->data['Transaction']['debit_money']
- $this->request->data['Transaction']['credit_money']
+ $this->Transaction->field('balance',array('Transaction.user_id'=> $client_id),
));

Resources