A
A
akula222016-03-22 14:47:57
Yii
akula22, 2016-03-22 14:47:57

What is the right way to make +1 in the news field when adding a comment?

There is a news module and a comment module, what is the correct way to add +1 to the field in the news table when adding a comment, and to do -1 when deleting a comment,
can events be used for this? I have never encountered them, maybe there is an example of implementation where to look?
Comments are not tied to news, they can be in photos, videos

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Kirill Arutyunov, 2016-03-24
@akula22

Use the updateCounters method to change the counter.
In general, if your site is not a highly loaded project, then there is not much point in keeping this field - one extra count() request will not cause big problems for the server.
Moreover, Yii provides convenient means for linking models.
Where comments are all comments, the hasMany() relationship in the model.

V
V Sh., 2016-03-22
@JuniorNoobie

We need the tables "News", "Comments" and the table "Comments_in_News" linking them. The last table contains the news Id and the comment Id. By simply counting the rows in this table (by a certain news Id), we get the number of comments. And if you add a rating, then the average rating ...

V
Vladimir Korovin, 2016-03-22
@vakorovin

It is a dubious idea to store an additional amount and constantly synchronize the real amount with this field. But. If you have already decided what you need, do it easier, solve this problem using the database itself, since they have been able to do this themselves for a long time. 3 triggers per comments table (insert, update, delete). And update the quantity field in the desired table. And then you don’t need to be tied to the framework, you never know who else will update these tables from where. As a guideline:

CREATE TRIGGER `insert_comment` AFTER INSERT ON `comments` FOR EACH ROW
BEGIN
  IF (NEW.material_type = 'post') THEN
    UPDATE posts SET comments_count = (SELECT COUNT(id) FROM comments WHERE material_id = NEW.material_id AND material_type = NEW.material_type) WHERE id = NEW.material_id;
  END IF;
END;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question