Home > PHP Framework > YII > body text

How to make the primary key automatically increase in Yii

angryTom
Release: 2020-02-26 17:17:21
Original
2867 people have browsed it

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 make the primary key automatically increase in Yii

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根据你的需求可以是正数也可以是负数。
Copy after login

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]);
Copy after login

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]
);
Copy after login

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]);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template