简体   繁体   中英

How to recalculate a field relating to another table (Yii2 MySQL)

I have MySQL database and table 'User' with field 'rating' in it. Also, I have 'Rating' table with 'user_id' and 'value' columns. I need to automatically get the medium value of the 'value' column in 'Rating' table and put it to the user's 'rating' field everytime someone votes for this user or just if we add/change rows in database. I tried "afterSave()" function in my Rating model in Yii2, but it only works if rating value is saved from form in view (by voting with radiobuttons). If I change values in database, it doesn't recalculate the 'rating' field, of course.I guess I need to do something with SQL, not with the framework, am I right? How is this usually done?

For your case you can use mysql triggers , that are sort of event handlers, that activates when a particular event occurs for the table eg INSERT , UPDATE or DELETE row. Here is an article about using triggers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM