Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize automatic accumulation of Yii2 data fields

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

Yii2 data fields how to achieve automatic accumulation, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.

Realize

Mode one

This updateAllCounters static method is available in Yii2, which is the fastest and most convenient way to implement. The code example is as follows:

Topic::updateAllCounters (['view_count' = > 1], [' id' = > $id]); / / the effect is that view_count + 1 can be positive or negative depending on your needs.

If your conditions are complicated, you can write:

Topic::updateAllCounters (['view_count' = > 1], [' and', ['xxx' = > 0,' yyy' = > 2], ['>', 'zzz', $time])

If your current requirement is to update the value of a field, the value of a field + 1, you can try to do so in this way:

Topic::updateAll (['view_count' = > new _ Expression (' `view_ count` + 1'), 'updated_at' = > time ()], [' id' = > $id])

PS: remember that the default value of the view_count field here cannot be set to null.

Expression means expression. You can implement more special SQL. If you want to know more, you can search the document.

Mode two

Of course, you can also do this:

$model = Post::findOne ($id); $model- > updateCounters (['view_count' = > 1]); is it helpful for you to read the above? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report