问题
I am trying to get the field totals for all results after filtering with the CakeDC search plugin.
In my model I have:
public function getFieldAmountTotal( $fieldNames){
// Can't use recursive -1 because it includes current filtering
// This will only grab the total by id
// Can't not pull id because filtering on related tables
//$totalAmounts = $this->find( 'all', array('fields' => $fieldNames));
$totalAmounts = $this->find( 'all', array('fields' => $fieldNames, 'group' => 'MovieStar.id'));
$grandTotal = array();
foreach($fieldNames as $fieldName){
$grandTotal[$fieldName] = 0;
}
foreach($totalAmounts as $amount){
foreach($fieldNames as $fieldName){
$grandTotal[$fieldName] += $amount['MovieStar'][$fieldName];
}
}
debug('$grandTotal');
debug($grandTotal);
return $grandTotal;
}
This worked great when I was using the CakePHP filter plugin because all filtering was stored in the session and was automatically passed in.
How would I filter in the find using the current filter plugin form settings?
回答1:
I figured out one way to do it. I pass the rows from the controller to the model.
Model:
public function getFieldAmountTotal($rowArray, $fieldNames){
// Can't use recursive -1 because it includes current filtering
// This will only grab the total by id
// Can't not pull id because filtering on related tables
//$totalAmounts = $this->find( 'all', array('fields' => $fieldNames));
$totalAmounts = $this->find( 'all', array('fields' => $fieldNames, 'group' => 'MovieStar.id'));
$grandTotal = array();
foreach($fieldNames as $fieldName){
$grandTotal[$fieldName] = 0;
}
//foreach($totalAmounts as $amount){
foreach($rowArray as $thisRow){
foreach($fieldNames as $fieldName){
$grandTotal[$fieldName] += $thisRow['MovieStar'][$fieldName];
}
}
debug('$grandTotal');
debug($grandTotal);
return $grandTotal;
}
Controller:
$this->Prg->commonProcess();
$this->paginate = array( 'conditions' => $this->MovieStar->parseCriteria($this->Prg->parsedParams()), 'limit' => 100);
$movieStars = $this->paginate();
// Get total amounts for stars
$amountFields = array('amount','loss_axis', 'loss_mgr1', 'loss_mgr2', 'loss_rep');
$reject_totals = $this->MovieStar->getFieldAmountTotal($movieStars, $amountFields);
Result:
array(
'amount' => (float) 4074.97,
'loss_axis' => (float) 22,
'loss_mgr1' => (float) 0,
'loss_mgr2' => (float) 0,
'loss_rep' => (float) 0
)
来源:https://stackoverflow.com/questions/22259893/cakephp-get-field-totals-after-search-plugin-filtering