简体   繁体   English

如何重新计算与另一个表相关的字段(Yii2 MySQL)

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

I have MySQL database and table 'User' with field 'rating' in it. 我有MySQL数据库和表“ User”,其中包含“ rating”字段。 Also, I have 'Rating' table with 'user_id' and 'value' columns. 另外,我有带有“ user_id”和“ value”列的“ Rating”表。 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). 我在Yii2的评分模型中尝试了“ afterSave()”功能,但只有在视图中从表单中保存评分值(通过单选按钮投票)时,该功能才有效。 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? 当然,如果我更改数据库中的值,它不会重新计算``评分''字段。我想我需要使用SQL而不是框架进行操作,对吗? 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. 对于您的情况,您可以使用mysql触发器 ,它们是事件处理程序,可在表的特定事件(例如INSERTUPDATEDELETE行)发生时激活。 Here is an article about using triggers. 这是有关使用触发器的文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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