Wednesday, May 7, 2014

Re: Containable and Aggregate fields

You may need to use the join option directly, instead of Containable.

http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#joining-tables

On Thursday, 8 May 2014 00:15:29 UTC+10, Harold Putman wrote:
I am trying to get a SUM of a column of related records through the Containable behavior. 
I've tried a number of variations based on information google turned up but I cannot get it to work:

$accounts = $this->find('all', array(
'contain' => array('Registration' => array('fields' => array('SUM(`credits`)'),
  'group' => array('Registration.account_id')))
));

I soon as I add the "group" part, I get: Model "Registration" is not associated with model "Registration"

Here's what I am trying to do in SQL:

SELECT
  accounts.*,
  SUM(registrations.credits) AS slot_count
FROM accounts
LEFT JOIN registrations
  ON (accounts.id=registrations.account_id)
  AND registrations.attend=1
GROUP BY accounts.id 

Maybe I need to just use that query directly instead of trying to use Containable? 

Thanks for any advice..

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP

---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/d/optout.

No comments: