【发布时间】:2018-07-17 04:13:06
【问题描述】:
一篇文章有多个cmet,每条评论都有一个评分栏。
当给文章添加新评论(分数)时,我想存储文章中所有 cmets 的平均值。
由于分数存储在每个评论中,在这种情况下-
1.所有cmet和新cmet的分数相加,除以cmet的数量。
2. 或者文章中存储的cmets的平均值可以乘以(cmets-1的数量),然后加上新评论的分数,再除以cmets的数量。
我尝试在 laravel querybuilder 中编写此代码,太难了。
如何在查询生成器中编码?
提前感谢您的帮助。
MariaDB []> desc articles;
+------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| user_id | int(10) unsigned | NO | MUL | NULL | |
| title | varchar(191) | NO | MUL | NULL | |
| content | text | NO | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
| average_score | int(11) | YES | | 0 | |
+------------+------------------+------+-----+---------+----------------+
MariaDB []> desc comments;
+------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| user_id | int(10) unsigned | YES | | NULL | |
| parent_id | int(10) unsigned | YES | | NULL | |
| commentable_type | varchar(255) | NO | | NULL | |
| commentable_id | int(10) unsigned | NO | | NULL | |
| content | text | NO | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
| deleted_at | timestamp | YES | | NULL | |
| score | int(11) | YES | | 0 | |
+------------------+------------------+------+-----+---------+----------------+
CommentsController.php
public function store(CommentsRequest $request, Article $article)
{
$comment = $article->comments()->create(array_merge(
$request->all(),
['user_id' => 'Guest']
));
#Here, the average value of comments is stored in $ article
...
}
【问题讨论】:
-
为什么要存储平均值,可以在运行时计算平均值
标签: php mysql laravel query-builder