Home >PHP Framework >YII >How to make the primary key automatically increase in Yii
Articles generally have a need to count the number of views. Generally, the approach for small projects is to directly update a field in the database. How to implement this in Yii? Please read below
How to automatically increase the primary key in yii
Method 1
Yii2 has this updateAllCounters static method. This method is the fastest and most trouble-free implementation. The code example is as follows:
Topic::updateAllCounters(['view_count' => 1], ['id' => $id]);// 实现的效果就是 view_count + 1,1根据你的需求可以是正数也可以是负数。
If your conditions are more complex, you can write like this: (Related tutorials recommend: yii Framework)
Topic::updateAllCounters(['view_count' => 1], ['and', ['xxx' => 0, 'yyy' => 2], ['>', 'zzz', $time]);
If your current need is to update the value of a field and the value of a field is 1, you can try to implement it 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, which can implement more special SQL. If you want to know more, you can search the documentation.
Method 2
当然你还可以这样去实现: $model = Post::findOne($id); $model->updateCounters(['view_count' => 1]);
For more programming tutorials, please pay attention to the PHP Chinese website!
The above is the detailed content of How to make the primary key automatically increase in Yii. For more information, please follow other related articles on the PHP Chinese website!