Hello everyone
I trying to do something like automatically calculate score field depended on a one-to-many relationship
So what my goal - do auto calculating score with just summarize all score of related one-to-many relationship record
For example, In Account module I created score field and it’s score should be the sum of all score records his subpanel Contacts (Account-contacts is a one-to-many relationship)
The formula = Account’s record score = score relationship1 + score relationship2 + score relationship3 …
The easiest way I think is to make MySQL triggers for it
I have already did triggers for insert, delete, update and all of them works well except of subpanel action
The subpanel action is adding exist record via choosing it from subpanel
What I expect when choosing a existing record = Contact record should recalculate (OLD)Account’s score and also recalculate (NEW)Account’s score
But it only recalculates (OLD)Account’s score and I don’t know why
I tested this ‘changing Account’ mechanism by Editview Contact and there is work well
Here is my MySQL trigger for this. It runs when OLD.id_organization != NEW.id_organization
id_organization is where I stored relationship ID (I rebuild my one-to-many relationship by ‘Suitecrm Nice Relationship’)
BEGIN
DECLARE oldAccountScore INT;
DECLARE newAccountScore INT;
IF OLD.id_organization != NEW.id_organization THEN
SET oldAccountScore = (SELECT organizations.score FROM organizations WHERE organizations.id = OLD.id_organization);
SET newAccountScore = (SELECT organizations.score FROM organizations WHERE organizations.id = NEW.id_organization);
UPDATE organizations SET score = oldAccountScore - OLD.score WHERE id = OLD.id_organization;
UPDATE organizations SET score = newAccountScore + NEW.score, description = 'by update' WHERE id = NEW.id_organization;
END IF;
END